如何处理与 python 套接字的断开连接? (连接重置错误)

Posted

技术标签:

【中文标题】如何处理与 python 套接字的断开连接? (连接重置错误)【英文标题】:How do I handle a disconnect with python sockets? (ConnectionResetError) 【发布时间】:2021-03-11 10:35:07 【问题描述】:

我正在使用 python 套接字制作一个简单的服务器和客户端,我想知道如何处理断开连接。每当我的一个客户端断开连接时,它会给出一个ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host 并且服务器停止运行。这是有道理的,但是我该如何处理这样的断开连接呢?这是我的服务器代码:(我知道它是我的第一个套接字项目)

import socket
import threading


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Connection oriented, IPV4

s.bind((socket.gethostname(), 1234))#Ip address information, port
s.listen(5)

connections = [] #Connection added to this list every time a client connects

def accptconnection():
    while True:
        clientsocket, address = s.accept()
        connections.append(clientsocket) #adds the clients information to the connections array
        threading.Thread(target=recvmsg, args=(clientsocket, address,)).start()

def recvmsg(clientsocket, address):
    while True:
        print(f"Connection from address has been established.")
        msg = clientsocket.recv(1024)
        if len(msg.decode('utf-8')) > 0:
            print(msg.decode("utf-8"))
        for connection in connections: #iterates through the connections array and sends message to each one
            msgbreak = msg
            connection.send(bytes(str(msgbreak.decode("utf-8")), "utf-8"))


accptconnection()

如果您能提供帮助,请提前致谢!

【问题讨论】:

【参考方案1】:

这应该可以防止服务器关闭,并清理您遇到连接错误的客户端:

import socket
import threading


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Connection oriented, IPV4

s.bind((socket.gethostname(), 1234))#Ip address information, port
s.listen(5)

connections = [] #Connection added to this list every time a client connects

def accptconnection():
    while True:
        clientsocket, address = s.accept()
        connections.append(clientsocket) #adds the clients information to the connections array
        threading.Thread(target=recvmsg, args=(clientsocket, address,)).start()

def recvmsg(clientsocket, address):
    print(f"Connection from address has been established.")
    while True:
        try:
            msg = clientsocket.recv(1024)
        except ConnectionError:
            print(f"Connection from address has been lost.")
            if clientsocket in connections:
                connections.remove(clientsocket)
            return
        if len(msg.decode('utf-8')) > 0:
            print(msg.decode("utf-8"))
        for connection in connections: #iterates through the connections array and sends message to each one
            msgbreak = msg
            try:
                connection.send(bytes(str(msgbreak.decode("utf-8")), "utf-8"))
            except ConnectionError:
                 print(f"Unable to reach client with socket connection")
                 if connection in connections:
                     connections.remove(connection)

accptconnection()

【讨论】:

谢谢!这很有帮助,我完全理解。

以上是关于如何处理与 python 套接字的断开连接? (连接重置错误)的主要内容,如果未能解决你的问题,请参考以下文章

如何处理与节点 ID 对应的响应对象?

如何处理与 RestKit 的关系同步(离线支持)

如何处理与 Laravel 的复杂关系?

如何处理与 AWS AppSync 离线同步的数据?

如何处理与派生类不兼容的基类方法?

Tornado Python 如何处理客户端连接丢失