猿问

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

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


慕姐4208626
浏览 301回答 1
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')
随时随地看视频慕课网APP

相关分类

Python
我要回答