-------------------server-------------------
!/usr/bin/python
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+=1
self.transport.write("欢迎,你是第{}客户".format(self.factory.numProtocols).encode("utf-8"))
clients.append(self)
def connectionLost(self,reason):
self.factory.numProtocols-=1
clients.remove(self)
print("lost connect: %d" % (self.factory.numProtocols))
def dataReceived(self,data):
if data=="close":
self.transport.lostConnection()
for client in clients:
if client!=self:
client.transport.write(data.encode("utf-8"))
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()
-------------------------------------------------client------------------------
!/usr/bin/python
coding=utf-8
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor
import threading
import time
import sys
import datetime
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)
bStop = False
def routine(factory):
while not bStop:
if factory.protocol and factory.protocol.connected:
factory.protocol.transport.write("hello, I'm {} {} ".format(
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