[英]Handling multiple connections in python with sockets
I have a code which works perfectly for one connection.我有一个代码可以完美地用于一个连接。 I have seen two options for multi-client handling but I don't really understand it.
我已经看到了多客户端处理的两种选择,但我并不真正理解它。 Here is the server socket code:
这是服务器套接字代码:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listening_sock:
listening_sock.bind(('', port))
listening_sock.listen()
client_soc, client_address = listening_sock.accept()
client_soc.sendall('200#Welcome to my server!'.encode())
print(f'Address {client_soc.getsockname()[0]} connected with port {client_soc.getsockname()[1]}')
while True:
# get message
msg = client_soc.recv(1024).decode()
# receive log print:
print(f'"{msg}" sent from {client_soc.getsockname()[0]}')
if 'Quit' in msg:
client_soc.sendall('200#Thanks for using my server!'.encode())
client_soc.close()
elif '0' < msg.split('#')[0] <= '9': # one of the valid actions
answer = call_action(msg.split('#')[0], db, msg.split('#')[1]) # the answer for given parameter
client_soc.sendall("200#".encode() + answer.encode())
If I have only one connection it works good and last thing I need to add is option for multiple-client handling.如果我只有一个连接,它工作得很好,我需要添加的最后一件事是用于多客户端处理的选项。 What is the shortest and easiest way to do it?
最短和最简单的方法是什么?
The code only calls accept
once.代码只调用一次
accept
。 Instead, call accept
in a while loop and create a thread for each client connection so they are handled in parallel.相反,在 while 循环中调用
accept
并为每个客户端连接创建一个线程,以便并行处理它们。 Use the following pattern as an example:使用以下模式作为示例:
import socket
import threading
# Thread to handle each "client_soc" connection
def handler(client_soc):
...
client_soc.close()
with socket.socket() as listening_sock:
listening_sock.bind(('', 8000))
listening_sock.listen()
while True:
client_soc, client_address = listening_sock.accept()
# Send each "client_soc" connection as a parameter to a thread.
threading.Thread(target=handler,args=(client_soc,), daemon=True).start()
There is also a built-in socket server that simplifies this process.还有一个内置的套接字服务器可以简化这个过程。 Here's a tested example echo server that echoes back newline-terminated data:
这是一个经过测试的示例回显服务器,它回显换行符终止的数据:
from socketserver import ThreadingTCPServer,StreamRequestHandler
class echohandler(StreamRequestHandler):
def handle(self):
print(f'Connected: {self.client_address[0]}:{self.client_address[1]}')
while True:
# get message
msg = self.rfile.readline()
if not msg:
print(f'Disconnected: {self.client_address[0]}:{self.client_address[1]}')
break # exits handler, framework closes socket
print(f'Received: {msg}')
self.wfile.write(msg)
self.wfile.flush()
server = ThreadingTCPServer(('',8000),echohandler)
server.serve_forever()
Your code blocks itself.您的代码会自行阻塞。
For instance: client_soc, client_address = listening_sock.accept()
Accepts client, then while True:
runs forever, so you can work with 1 connection only, because socket.accept()
is called once.例如:
client_soc, client_address = listening_sock.accept()
接受客户端,然后while True:
永远运行,因此您只能使用 1 个连接,因为socket.accept()
被调用一次。 You should learn some of these to solve your problem: asyncio, threading, multiprocessing.您应该学习其中的一些来解决您的问题:异步、线程、多处理。 These libraries will help your code to accept and work with clients concurrently.
这些库将帮助您的代码同时接受和使用客户端。 Sockets can use every, but often they are paired with asyncio: https://asyncio.readthedocs.io/
Sockets 可以使用每一个,但通常它们与 asyncio 配对: https://asyncio.readthedocs.io/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.