一个事件驱动的网络引擎。
服务器
from twisted.internet import protocol,reactor
from time import ctime
PORT = 10001
class TSServerProtocol(protocol.Protocol):
def connectionMade(self):
client = self.client = self.transport.getPeer().host
print('等待链接,来自:',client)
def dataReceived(self, data):
data = data.decode()
print(data)
self.transport.write('[%s]%s'%(ctime(),data).encode())
factory = protocol.Factory()
factory.protocol = TSServerProtocol
print('等待链接:')
reactor.listenTCP(PORT,factory)
reactor.run()
服务器
from twisted.internet import protocol,reactor
HOST = ''
PORT = 10001
class TSClientProtocol(protocol.Protocol):
def sendData(self):
data = input('')
if data:
print('正在发送:',data)
self.transport.write(data.encode())
def connectionMade(self):
self.sendData()
def dataReceived(self, data):
print(data.encode())
self.sendData()
class TSClientFactory(protocol.ClientFactory):
protocol = TSClientProtocol
reactor.connectTCP(HOST,PORT,TSClientFactory)
reactor.run()