我有这个聊天服务器代码,消息传递基本上不起作用,我用 telnet 测试它,它没有发送任何东西,我将它发送回客户端。我知道客户端已连接,实际上整个 wait_for_connection() 工作正常。我感觉这与我对 python 中的多线程知识的不好有关。有人可以纠正我吗?
import socket, thread, sys
connections = []
isRunning = True
def wait_for_connection():
while isRunning:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("", 1234))
s.listen(5);
print "Server is listening"
con, addr = s.accept()
print "Connected to", addr
connections.append(con)
def loop_through_connections():
for con in connections:
con.setblocking(0)
while isRunning:
for con in connections:
data = con.recv(100)
if not data:
break
for connection in connections:
connection.send(data)
if __name__ == "__main__":
thread.start_new_thread(wait_for_connection, ())
thread.start_new_thread(loop_through_connections, ())
while isRunning:
pass