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

Problems with self.transport.write() for Twisted TCP client in Python

我在 python 中有一个非常基本的扭曲 server/client 设置。

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)"。或者至少我认为它确实如此,因为打印到控制台的最后一件事是 'sending message'.

我已经搜索了好几天,但似乎无法找出问题所在(我对网络还很陌生)。我在这里做错了什么?我正在使用 Python 3 和 运行ning 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')