【发布时间】:2014-10-14 21:53:40
【问题描述】:
我使用如下线程制作了一个简单的聊天服务器:
#-*- coding:utf-8 -*-
import _thread as thread
import time
import socket
def now():
return time.asctime(time.localtime())
def handleclient(connection, ADDR):
sod = str(ADDR)
msg = sod+"joined the chat"
msg2 = msg.encode("utf-8")
connection.sendall(msg2)
while True:
recieved = connection.recv(1024)
adsf = recieved.decode("utf-8")
print(now(),"(%s):%s" % (ADDR, recieved))
output = "%s:%s"%(ADDR, recieved.decode("utf-8"))
message = output.encode("utf-8")
connection.sendall(message)
if __name__ == "__main__":
addr = ("", 8080)
r =socket.socket()
print("socket object created at", now())
r.bind(addr)
r.listen(5)
while True:
print("Waiting for clients...")
connection, ADDR = r.accept()
print("We have connection from ", ADDR)
thread.start_new_thread(handleclient, (connection, ADDR))
但是,sendall 似乎不起作用,并且仅将消息发送给发送它的人。我怎样才能让它发送给所有客户?
【问题讨论】:
-
这不是
sendall()所做的。你被它的名字弄糊涂了。 -
@Ashwini Chaudhary 哦。它完全与我想要做的不同。有什么解决办法吗?
-
您必须在此处、列表或字典中跟踪连接对象,并在连接丢失后将其删除。但这会很棘手,因为涉及线程。这就是说我个人更喜欢Twisted 在套接字方面,与线程方式相比,它更易于使用和维护。 Twisted 中的简单聊天服务器示例:twistedmatrix.com/documents/12.3.0/core/examples/chatserver.py
-
看起来我的线程、解决方案、代码here 可能会有所帮助。