開發(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