Python中Twisted TCP客户端的self.transport.write()问题

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (276)

我在python中有一个非常基本的扭曲服务器/客户端设置。

server.py:

from twisted.internet.protocol import Protocol
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class 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 reactor
from twisted.internet.protocol import Protocol
from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol

class 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 = 9009
point = 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。

提问于
用户回答回答于

它不会卡在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')

扫码关注云+社区

领取腾讯云代金券