【发布时间】:2020-05-20 10:54:52
【问题描述】:
我有一个代码可以完美地用于一个连接。我已经看到了多客户端处理的两种选择,但我并不真正理解它。 这是服务器套接字代码:
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())
如果我只有一个连接,它工作得很好,最后我需要添加的是多客户端处理选项。最短和最简单的方法是什么?
【问题讨论】:
标签: python sockets networking connection