client端
server端
#!/usr/bin/python
# -*- coding: utf-8 -*-
from twisted.internet import reactor, protocol
class EchoClient(protocol.Protocol):
#建立连接后调用的事件
def connectionMade(self):
#把数据输出到服务器端
self.transport.write(bytes("hello dongxu!","utf8"))
#连接建立有数据接收到的时候会调用的方法
def dataReceived(self, data):
#打印收到的数据
print("Server said:", data.decode("utf8"))
#客户端主动关闭掉连接
self.transport.loseConnection()
#连接关闭掉后调用的方法
def connectionLost(self, reason):
print("connection lost")
#protocol的ClientFactory
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
#当服务端或者网络原因连接失败的时候
def clientConnectionFailed(self, connector, reason):
print("Connection failed - goodbye!")
reactor.stop()
#正常断开连接的时候调用的方法
def clientConnectionLost(self, connector, reason):
print("Connection lost - goodbye!")
#停止reactor事件
reactor.stop()
def main():
f = EchoFactory()
#与localhost 1234端口建立连接
reactor.connectTCP("localhost", 1234, f)
reactor.run()
if __name__ == '__main__':
main()
server端
#!/usr/bin/python
# -*- coding: utf-8 -*-
from twisted.internet import protocol
from twisted.internet import reactor
class Echo(protocol.Protocol):
def dataReceived(self, data):
self.transport.write(data)
def main():
factory = protocol.ServerFactory()
factory.protocol = Echo
#监听1234端口 建立TCP连接
reactor.listenTCP(1234,factory)
reactor.run()
if __name__ == '__main__':
main()