服务器端代码
# -*- coding:UTF-8 -*-
from time import ctime
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, Factory
PORT = 21567
class TSServProtocol(Protocol):
def connectionMade(self):
clnt = self.clnt = self.transport.getPeer().host
print '...connected from :', clnt
def dataReceived(self, data):
self.transport.write('[%s] %s' % (ctime(), data))
factory = Factory()
factory.protocol = TSServProtocol
print 'waiting for connection...'
reactor.listenTCP(PORT, factory)
reactor.run()
客户端代码
# -*- coding:UTF-8 -*-
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, ClientFactory
HOST = 'localhost'
PORT = 21567
class TSClntProtocol(Protocol):
def sendData(self):
data = raw_input('> ')
if data:
print '...sending %s...' % data
self.transport.write(data)
else:
self.transport.loseConnection()
def connectionMade(self):
self.sendData()
def dataReceived(self, data):
print data
self.sendData()
class TSClntFactory(ClientFactory):
protocol = TSClntProtocol
clientConnectionLost = clientConnectionFailed = \
lambda self, connector, reason: reactor.stop()
reactor.connectTCP(HOST, PORT, TSClntFactory())
reactor.run()