我在python中有一个非常基本的扭曲服务器/客户端设置。server.py:from twisted.internet.protocol import Protocolfrom twisted.internet.protocol import Factoryfrom twisted.internet.endpoints import TCP4ServerEndpointfrom twisted.internet import reactorclass Echo(Protocol): def __init__(self, factory): self.factory = factory def connectionMade(self): print("Connection made") def connectionLost(self): print("Connection lost") def dataReceived(self, data): print("Received data") print(data) self.transport.write(data)class EchoFactory(Factory): def buildProtocol(self, addr): return Echo(self)def main(): PORT = 9009 #the port you want to run under. Choose something >1024 endpoint = TCP4ServerEndpoint(reactor, PORT) endpoint.listen(EchoFactory()) reactor.run()if __name__ == "__main__": main()client.py:from twisted.internet import reactorfrom twisted.internet.protocol import Protocolfrom twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocolclass Greeter(Protocol): def sendMessage(self, msg): print('sending message') self.transport.write("MESSAGE %s\n" % msg) print('message sent')def gotProtocol(p): p.sendMessage("Hello") reactor.callLater(1, p.sendMessage, "This is sent in a second") reactor.callLater(2, p.transport.loseConnection)PORT = 9009point = TCP4ClientEndpoint(reactor, "localhost", PORT)d = connectProtocol(point, Greeter())d.addCallback(gotProtocol)print('running reactor')reactor.run()当我使用Telnet客户端ping服务器并收到预期的响应时,服务器工作正常。但是,当我尝试运行client.py时,它卡在了“ self.transport.write(” MESSAGE%s \ n“%msg)”处。或者至少我认为是这样做的,因为打印到控制台的最后一件事是“发送消息”。我已经搜索了几天,但似乎无法弄清楚出了什么问题(我是网络新手)。我在这里做错了什么?我正在使用Python 3并正在运行Windows 8.1。
1 回答
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
它不会卡在self.transport.write("MESSAGE %s\n" % msg)它实际上在那里失败。Transport.write只接受bytes。对该字符串进行编码,它应该可以工作。
class Greeter(Protocol):
def sendMessage(self, msg):
print('sending message')
self.transport.write(("MESSAGE %s\n" % msg).encode('utf8'))
print('message sent')
添加回答
举报
0/150
提交
取消