为什么几次消息后此Python3聊天失败?

时间:2019-01-17 12:59:35

标签: python-3.x chat

发生的事情是:客户端发送一些消息后,它会显示ConnectionAbortedError:[WinError 10053],并且服务器将继续运行

图片:

服务器套接字: enter image description here

客户端套接字: enter image description here

这是我的服务器代码:

from socket import *

def server(address, port):
    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind((address, port))
    sock.listen(10)
    while True:
        clientsock, addr = sock.accept()
        ip, _ = addr
        msg = input('YOU: ')
        clientsock.send(bytes(msg, 'utf-8'))
        data = clientsock.recv(2048)
        print('%s - ' % ip, data.decode('utf-8'))
        if not data:
            break
        clientsock.shutdown(SHUT_WR)
        clientsock.close()
    sock.close()

if __name__ == '__main__':
    server('192.168.0.101', 5000)

客户:

from socket import *

def client(address, port):
    sock = socket(AF_INET, SOCK_STREAM)
    sock.connect((address, port)) #0.0.0.0 isnt valid
    while True:
        data = sock.recv(2048)
        print('%s - ' % address, data.decode('utf-8'))
        msg = input('YOU: ')
        sock.send(bytes(msg, 'utf-8'))
    sock.close()

if __name__ == '__main__':
    client('192.168.0.101', 5000)

1 个答案:

答案 0 :(得分:0)

每个循环中的服务器接受新客户端发送一条消息,接收一条消息并断开客户端连接。然后,它等待另一个客户端。

您需要另一个循环来处理客户端。

另一个循环可以放在另一个线程中。

如果将该循环嵌套在此循环中,则您一次只能处理一个客户端。我这样修改了您的服务器:

def server(address, port):
    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind((address, port))
    sock.listen(10)
    while True: # server loop
        clientsock, addr = sock.accept()
        ip, _ = addr
        msg = "Hello to client from %s" % ip
        # next line is here because your client need message from server to send message
        clientsock.send(bytes(msg, 'utf-8'))  
        while True: #  client loop
            data = clientsock.recv(2048)
            msg = '%s - %s' % (ip, data.decode('utf-8'))
            print(msg)
            if not data:
                break
            clientsock.send(bytes(msg, 'utf-8'))  # for multiple clients you need send msg to all
        clientsock.shutdown(SHUT_WR)
        clientsock.close()
    sock.close()

要处理多个客户端,您不希望在客户端循环结束之前阻止服务器循环。您可以在另一个线程中运行客户端循环,然后继续等待下一个客户端clientsock, addr = sock.accept()

类似地,您可能希望将接收邮件与服务器分开,并等待客户端输入。