Python Twisted學習

開發(fā)環(huán)境

1.Visual Studio Code

安裝python extension,我使用的本地python版本是3.6.6,也可以安裝2.7隨時進行切換

2.Twisted安裝

Windows環(huán)境下需先安裝pywin32包

pip install pywin32

安裝成功后繼續(xù)安裝Twisted包,安裝的同時會自動安裝zope.interface

pip install twisted

Twisted基礎(chǔ)

Twisted的三個基礎(chǔ)模塊:Protocol,ProtocolFactory,Transport.

Protocol:實現(xiàn)協(xié)議內(nèi)容,即通信的內(nèi)容協(xié)議

ProtocolFactory:生成協(xié)議的工廠

Transport:數(shù)據(jù)的收發(fā)處理

廣播服務器代碼

# 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

演示效果


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容