我正在使用twisted python进行多客户聊天服务器程序。在我的程序中,如果我们从一个客户端发送“list”,则服务器必须将连接的客户端列表发送到该客户端。此外,当我们从一个客户端发送“talk clientname message”时,服务器必须将该消息发送到“clientname”中指定的目标客户端。但我的代码不起作用。服务器有错误。不显示列表,也没有说话。
我的服务器代码如下:
class MultiEcho(Protocol):
def __init__(self, factory):
self.factory = factory
def connectionMade(self):
self.factory.clients.append(self)
def dataReceived(self,data):
data = data.strip()
if (data == "list"):
for client in self.factory.clients:
print self.factory.clients
self.transport.write(self.factory.clients)
else:
data = data.split()
if (len(data) > 1):
l = data[1]
m = data[2]
l.transport.write(m)
def connectionLost(self,reason):
self.factory.clients.remove(self)
class MultiEchoFactory(Factory):
def __init__(self):
self.clients = []
def buildProtocol(self, addr):
return MultiEcho(self)
if __name__ == '__main__':
import sys
if len(sys.argv) != 4:
print "Sorry.. not correct.. Try Again!"
sys.exit(1)
else:
if (sys.argv[1] == "chatserver") and (sys.argv[2] == "-p"):
PORT = sys.argv[3]
reactor.listenTCP(8000, MultiEchoFactory())
reactor.run()
请有人给我解决方案吗
答案 0 :(得分:1)
dataReceived()
收到的数据量。您可能需要从LineReceiver
继承并使用lineReceived()
逐行处理输入。transport.write()
接受字符串,而不是列表。您需要为客户定义clientname
,例如,工厂应该能够根据其名称找到客户。然后你可以在LineReceived()
:
command, _, rest = line.partition(command_separator)
if command == "talk":
clientname, _, message = rest.partition(arg_separator)
self.factory.getClient(clientname).sendLine(message)