1
我有這個聊天服務器代碼和消息傳遞基本上不起作用,即時通訊測試它與遠程登錄,它不發送任何我發回給客戶端。我知道客戶端已連接,事實上整個wait_for_connection()工作正常。我有一種感覺,它與我在python中多線程的不良知識有關。有人能糾正我嗎?簡單的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