我正在尝试使用线程来处理每个客户端的服务器客户端程序,但服务器一次只接受一个客户端。如果第一个客户端断开连接,则接受第二个客户端。此外,每个客户端只能发送一次数据,然后程序无法再发送。
在发布之前,我查看了许多其他Stack Overflow帖子,包括以下内容:
how can I make a server communicate with more than 1 client at the same time?
My Python socket server can only receive one message from the client
但是通过查看这些帖子,我找不到任何解决方案。
这是服务器代码:
import socket
from threading import *
def main():
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('172.20.3.62', 5000))
s.listen(1)
clients = []
print("listening")
def clienthandler(c):
clients.append(c)
try:
while True:
data = c.recv(1024).decode("UTF-8")
if not data:
break
else:
print(data)
for client in clients:
client.send(data.encode("UTF-8"))
except:
clients.remove(c)
c.close()
while True:
c, addr = s.accept()
print("accepted a client")
Thread(target=clienthandler(c)).start()
if __name__ == '__main__':
main()
以下是客户端代码:
import socket
from threading import *
def main():
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('172.20.3.62', 5000))
print("connected")
def send():
msg = input("ENTER:")
s.send(msg.encode("UTF-8"))
def receive():
while True:
data = s.recv(1024).decode("UTF-8")
if data:
print(data)
else:
break
Thread(target=send).start()
Thread(target=receive).start()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
感谢用户Rawing。他/她的解决方案是:线程(目标= clien thandler(c)) - >线程(target = clien thandler,args =(c,)) 这允许多个线程,并且我能够通过将客户端发送块放在while循环中来解决唯一的消息问题。