Python Twisted学习

开发环境

1.Visual Studio Code

安装python extension,我使用的本地python版本是3.6.6,也可以安装2.7随时进行切换

2.Twisted安装

Windows环境下需先安装pywin32包

pip install pywin32

安装成功后继续安装Twisted包,安装的同时会自动安装zope.interface

pip install twisted

Twisted基础

Twisted的三个基础模块:Protocol,ProtocolFactory,Transport.

Protocol:实现协议内容,即通信的内容协议

ProtocolFactory:生成协议的工厂

Transport:数据的收发处理

广播服务器代码

# coding=utf-8

from twisted.internet.protocol import Protocol

from twisted.internet.protocol import Factory

from twisted.internet.endpoints import TCP4ServerEndpoint

from twisted.internet import reactor

clients = []

class Spreader(Protocol):

    def __init__(self, factory):

        self.factory = factory

    def connectionMade(self):

        self.factory.numProtocols = self.factory.numProtocols + 1

        self.transport.write(

            (u"欢迎来到Spread Site, 你是第%s个客户端用户!\n" % (self.factory.numProtocols)).encode('utf-8')

        )

        print("new connect: %d" % (self.factory.numProtocols))

        clients.append(self)

    def connectionLost(self, reason):

        self.factory.numProtocols = self.factory.numProtocols - 1

        clients.remove(self)

        print ("lost connect: %d" % (self.factory.numProtocols))

    def dataReceived(self, data):

        if data == "close":

            self.transport.loseConnection()

            for client in clients:

                if client != self:

                    client.transport.write(data)

        else:

            print (data)

class SpreadFactory(Factory):

    def __init__(self):

        self.numProtocols = 0

    def buildProtocol(self, addr):

        return Spreader(self)

endpoint = TCP4ServerEndpoint(reactor, 8007)

endpoint.listen(SpreadFactory())

reactor.run()

客户端代码

# coding=utf-8

from twisted.internet.protocol import Protocol, ClientFactory

class Echo(Protocol):

    def __init__(self):

        self.connected = False

    def connectionMade(self):

        self.connected = True

    def connectionLost(self, reason):

        self.connected = False

    def dataReceived(self, data):

        print (data.decode("utf-8"))

class EchoClientFactory(ClientFactory):

    def __init__(self):

        self.protocol = None

    def startedConnecting(self, connector):

        print ("Start to Connect...")

    def buildProtocol(self, addr):

        print ("Connected...")

        self.protocol = Echo()

        return self.protocol

    def clientConnectionLost(self, connector, reason):

        print ("Lost connection. Reason: ", reason)

    def clientConnectionFailed(self, connector, reason):

        print ("Connection is failed, Reason: ", reason)

from twisted.internet import reactor

import threading

import time

import sys

import datetime

bStop = False

def routine(factory):

    while not bStop:

        if factory.protocol and factory.protocol.connected:

            factory.protocol.transport.write(("hello, I'm %s %s" % (

                sys.argv[0], datetime.datetime.now()

            )).encode('utf-8'))

            print (sys.argv[0], datetime.datetime.now())

        time.sleep(5)

host = "127.0.0.1"

port = 8007

factory = EchoClientFactory()

reactor.connectTCP(host, port, factory)

threading.Thread(target=routine, args=(factory,)).start()

reactor.run()

bStop = True

演示效果


你可能感兴趣的:(Python Twisted学习)