我有以下代码(几乎是列出here的聊天服务器示例的精确副本:
import twisted.scripts.twistd 来自twisted.protocols导入基本 来自twisted.internet导入协议,reactor 来自twisted.application导入服务,互联网
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
if __name__ == "__main__":
print "Building reactor...."
reactor.listenTCP(50000, factory)
print "Running ractor...."
reactor.run()
else:
application = service.Application("chatserver")
internet.TCPServer(50000, factory).setServiceParent(application)
服务器运行没有错误,如果我通过Telnet连接它,我可以发送数据,服务器打印到控制台并将其中继到所有客户端(如预期的那样)。但是,如果我通过不同的工具(MUD客户端)连接它,它永远不会获取数据。
我已经确保客户端正在发送数据(使用Wireshark跟踪数据包,并且它们正在通过线路),但服务器要么从未收到它,要么出于某种原因选择忽略它。
我尝试过两个MUD客户端,gmud和JMC。如果它很重要,我运行的是Windows 7 x64。
有谁知道为什么会发生这种情况?
谢谢,
麦克
修改
感谢Maiku Mori提供的提示,我尝试添加Twisted API Docs中指定的另一种方法dataReceived。添加完成后,MUD客户端工作正常,但Telnet现在发送每个字符作为自己的数据集,而不是等待用户按Enter键。
这是一段新代码:
def dataReceived(self, data):
print "Dreceived", repr(data)
for c in self.factory.clients:
c.message(data)
# def lineReceived(self, line):
# print "received", repr(line)
# for c in self.factory.clients:
# c.message(line)
以前有没有人经历过这种情况,如果有的话,你是如何解决这个问题的?理想情况下,我希望Telnet 和 MUD客户端能够使用此应用程序。
再次感谢。
答案 0 :(得分:3)
如果有人遇到类似问题而遇到这个问题,我会把我的发现留作接受的答案,这样人们就不必像我那样去打猎了。
我通过将我的Twisted协议中的分隔符值从“\ r \ n”(默认)更改为“\ n”(这是我的MUD客户端发送的内容)来修复此问题。这意味着在Telnet中,你输入字符串:
Hello, World
您的申请将收到:
Hello, World\r
您可能需要在服务器端进行数据卫生以保持秩序正常。我的最终代码如下:
import twisted.scripts.twistd 来自twisted.protocols导入基本 来自twisted.internet导入协议,reactor 来自twisted.application导入服务,互联网
class MyChat(basic.LineReceiver):
def __init__(self):
self.delimiter = "\n"
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.message(line)
def message(self, message):
self.transport.write(message + '\n')
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
if __name__ == "__main__":
print "Building reactor...."
reactor.listenTCP(50000, factory)
print "Running ractor...."
reactor.run()
else:
application = service.Application("chatserver")
internet.TCPServer(50000, factory).setServiceParent(application)
感谢您的帮助。
答案 1 :(得分:1)
您确定MUD客户端在每行之后发送行结束字符吗?只有在发送了行结束字符后才会调用 lineReceived 。
编辑:
我在这里找到了LineReceiver的API文档。您可以使用 dataReceived 方法来查看您是否真正获得了任何类型的数据。如果我记得你可以像 lineReceived 那样使用它。