【发布时间】:2020-11-25 21:42:36
【问题描述】:
我正在制作一个脚本,允许多个客户端查看来自服务器脚本的实时摄像机镜头,这一切正常,直到其中一个客户端脚本关闭,然后引发 ConnectionResetError,为避免这种情况,我使用了尝试和 except 块来捕获 ConnectionResetError 但每次连接丢失后都会引发相同的错误。仅使用socket.recv 会停止ConnectionResetError,但socket.recv 不会返回脚本将视频流发送回客户端所需的发件人地址。
服务器:
host = "0.0.0.0"
port = 5000
buffer_size = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("", port))
listeners = list() # the addresses of the clients that want the video stream
def handle_queue(sock):
while True:
try:
message, address = sock.recvfrom(buffer_size) # block the thread until a packet arrives
print(address)
message = str(message, "utf-8") # decode the message
if message == "join":
listeners.append(address) # add the list of listeners
else:
print("unknown queue msg: ", message)
except ConnectionResetError:
print("The connection was forcefully quit")
queue_handler_thread = Thread(target=handle_queue, args=(sock,), daemon=True)
queue_handler_thread.start() # start the queue
脚本然后对listeners 列表中的每个地址使用 sock.sendto()
客户:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(bytes("join","utf-8"), (host, port))
while True:
data, address = sock.recvfrom(max_length) # block main thread until a packet is received
【问题讨论】:
标签: python python-3.x sockets networking udp