0

嗨,我正在关注 Tim 的关于套接字的技术教程,我正在构建一个聊天应用程序,我正在尝试创建一个包含名称和 IP 的字典。但是当我连接并输入我的名字时,客户端应用程序会冻结,但我不知道为什么你可以看看你是否可以帮助我这是代码。服务器端代码

import socket
import threading
import io

HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "dis"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
Names = {}


def handle_client(conn, addr):
    print(f"[NEW CONNECTION] {addr} connected.")

    connected = True
    while connected:
        msg_length = conn.recv(HEADER).decode(FORMAT)
        if msg_length:
            msg_length = int(msg_length)
            msg = conn.recv(msg_length).decode(FORMAT)
            if msg.split(':::')[0] == 'Name':
                name = msg.split(':::')[-1]
                Names[addr] = name
                print(Names.get(addr))
            elif msg == DISCONNECT_MESSAGE:
                connected = False
                print(f'[{addr}] Has disconnected')
                # Names.pop(addr)

            else:
                conn.send('message recieved'.encode(FORMAT))
                print(msg)

    conn.close()


def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")


print("[STARTING] server is starting...")
start()

这是客户端代码

import socket

HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "dis"
SERVER = '127.0.1.1'
print(SERVER)
Name = input('Enter your name: ')
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)

def send(msg):
    message = msg.encode(FORMAT)
    msg_length = len(message)
    send_length = str(msg_length).encode(FORMAT)
    send_length += b' ' * (HEADER - len(send_length))
    client.send(send_length)
    client.send(message)
    print(client.recv(2048).decode(FORMAT))
send('Name:::' + Name)
while True:
    msg = input('what message do you want to send type dis to disconnect: ')
    if msg != DISCONNECT_MESSAGE :
        send(msg)
    elif msg == DISCONNECT_MESSAGE:
        send(msg)
        break
    elif msg == None:
        print("please type a message and don't leave it a blank")


4

1 回答 1

0

在您的客户端代码中,在功能下send(msg),一旦客户端发送消息,您就会期待服务器的响应,并且您也使用相同的功能来发送用户名。

在服务器中,您尚未编码以响应用户名。

因此,您的客户端实际上正在等待服务器的响应,即它刚刚发送的用户名。这就是它看起来冻结的原因。
在服务器中添加响应Hello username将解决此问题。

服务器

import socket
import threading
import io

HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "dis"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
Names = {}


def handle_client(conn, addr):
    print(f"[NEW CONNECTION] {addr} connected.")

    connected = True
    while connected:
        msg_length = conn.recv(HEADER).decode(FORMAT)
        if msg_length:
            msg_length = int(msg_length)
            msg = conn.recv(msg_length).decode(FORMAT)
            if msg.split(':::')[0] == 'Name':
                name = msg.split(':::')[-1]
                Names[addr] = name
                print(Names.get(addr))
                conn.send(f'Hello {name}'.encode(FORMAT))
            elif msg == DISCONNECT_MESSAGE:
                connected = False
                print(f'[{addr}] Has disconnected')
                # Names.pop(addr)

            else:
                conn.send('message recieved'.encode(FORMAT))
                print(msg)

    conn.close()


def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")


print("[STARTING] server is starting...")
start()
于 2020-09-19T11:35:31.213 回答