python 简单使用twisted,简单demo

简单使用twisted

步骤
1、下载twisted:

pip install twisted

2、代码
1、实例化一个Factory
2、让自己写的Protocol的子类作为实例化的Factory的protocol属性
3、reactor监听、启动

from twisted.internet import reactor, protocol
from twisted.internet.protocol import connectionDone

# 继承protocol.Protocol
# 并重写其中的几个重要方法
class Echo(protocol.Protocol):
    """This is just about the simple possible protocol
    """

    def dataReceived(self, data):
        # 接收到数据,立即返回
        # self.transport.write(data)
        print data

    def connectionMade(self):
        # 接收到连接请求
        pass

    def connectionLost(self, reason=connectionDone):
        # 断开连接
        print '客户端断开连接'

def main():
    """this runs the protocol on port 8000"""
    # 实例化一个Factory
    factory = protocol.Factory()
    # 让自己写的Protocol的子类作为实例化的Factory的protocol属性
    factory.protocol = Echo
    # 监听的端口是估计是0.0.0.0,所以不用设置特定的ip
    # reactor监听、启动
    reactor.listenTCP(8000, factory)
    reactor.run()

if __name__ == '__main__':
    main()

随便写一个客户端

import socket

client = socket.socket()
client.connect(("127.0.0.1", 8000))
client.send("hello world")

先启动server,在启动client,执行结果

hello world
客户端断开连接
其中也有很多有用的方法,这里用循环调用来举例
# -*- coding: utf-8 -*- 
# @Time     : 2020/8/18 15:30 
# @Author   : [email protected]
# @desc:    : 这个文件是测试twisted的类
from twisted.internet import reactor, protocol, task
from twisted.internet.protocol import connectionDone

# 继承protocol.Protocol
# 并重写其中的几个重要方法
class Echo(protocol.Protocol):
    """This is just about the simple possible protocol
    """

    def dataReceived(self, data):
        # 接收到数据,立即返回
        # self.transport.write(data)
        print data

    def connectionMade(self):
        # 接收到连接请求
        pass

    def connectionLost(self, reason=connectionDone):
        # 断开连接
        print '客户端断开连接'

def main():
    """this runs the protocol on port 8000"""
    factory = protocol.Factory()
    factory.protocol = Echo
    # 监听的端口是估计是0.0.0.0,所以不用设置特定的ip

	# 声明循环的task,里面接收的是一个func,返回的是LoopingCall对象
	# 使用start()开始,里面接受一个时间间隔
    server_time_loop = task.LoopingCall(time_task)
    server_time_loop.start(1)

    reactor.listenTCP(8000, factory)
    reactor.run()


def time_task():
    print '被调用了'

if __name__ == '__main__':
    main()

这是最基本的用法,深入研究,下面是官网:
Twisted
github
twisted

猜你喜欢

转载自blog.csdn.net/qq_40666620/article/details/108081789