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

时间:2018-08-02 21:30:25

标签: python twisted

我在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。

1 个答案:

答案 0 :(得分:0)

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