twisted

client端

#!/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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值