python核心程式設計,使用了twisted.internet類建立一個簡單的半雙工聊天程式
Server部分:
'''
Created on 2018年5月6日
一個時間戳TCP伺服器,他使用了twisted.internet類
@author: Administrator
'''
from twisted.internet import protocol,reactor
from time import ctime
from hexinbiancheng.utils.tsTclntEntity import Tserver
PORT = 21567
# ts = Tserver()
# HOST = ts.host
# PORT = ts.port
class TSServProtocol(protocol.Protocol):
def sendData(self):
data = input('> ')
if data:
#print('...sending %s...' % data)
self.transport.write(data.encode())
print('我說: ' + ('[%s] %s' % (ctime(), data)))
else:
self.transport.loseConnection()
# def connectionMade(self):
# data = None
# if not data:
# """傳送資料"""
# self.sendData()
#
# """列印連線資訊"""
#clnt = self.clnt = self.transport.getPeer().host
#print('Server...connected from :', clnt)
def dataReceived(self, data):
if data:
#data有值
"""處理資料並返回給請求方"""
#self.transport.write(('[%s] %s' % (ctime(), data.decode())).encode())
print('別人說: ' + ('[%s] %s' % (ctime(), data.decode())))
self.sendData()
else:
#data為None
"""傳送資料"""
#print('Server' + data.decode())
self.sendData()
class TSClntFactory(protocol.ClientFactory):
protocol = TSServProtocol
clientConnectionLost = clientConnectionFailed = \
lambda self, connector, reason: reactor.stop()
"""客戶端建立連線協議物件"""
#reactor.connectTCP(HOST, PORT, TSClntFactory())
"""服務端建立連線協議物件"""
factory = protocol.Factory()
factory.protocol = TSServProtocol
print('服務端waiting for connection...')
reactor.listenTCP(PORT, factory)
reactor.run()
Client部分:
'''
Created on 2018年5月6日
這個指令碼建立一個TCP客戶端,它提示使用者輸入傳送到伺服器端的訊息,並接收從伺服器端返回的添加了時間戳字首的相同訊息,然後將結果展示給使用者。
@author: Administrator
'''
from twisted.internet import protocol, reactor
from hexinbiancheng.utils.tsTclntEntity import Tserver
from time import ctime
HOST = '127.0.0.1'
PORT = 21567
# ts = Tserver()
# HOST = ts.host
# PORT = ts.port
class TSClntProtocol(protocol.Protocol):
#全域性變數data,用來儲存訊息
#data = ''
def sendData(self):
data = input('> ')
if data:
#print('...sending %s...' % data)
self.transport.write(data.encode())
print('我說: ' + ('[%s] %s' % (ctime(), data)))
else:
self.transport.loseConnection()
def connectionMade(self):
data = None
if not data:
"""傳送資料"""
self.sendData()
"""列印連線資訊"""
#clnt = self.clnt = self.transport.getPeer().host
#print('Client...connected from :', clnt)
def dataReceived(self, data):
if data:
#data有值
"""處理資料並返回給請求方"""
#self.transport.write(('[%s] %s' % (ctime(), data.decode())).encode())
#print('Client: ' + data.decode())
print('別人說: ' + ('[%s] %s' % (ctime(), data.decode())))
self.sendData()
else:
#data為None
"""傳送資料"""
#print('Server' + data.decode())
self.sendData()
class TSClntFactory(protocol.ClientFactory):
protocol = TSClntProtocol
clientConnectionLost = clientConnectionFailed = \
lambda self, connector, reason: reactor.stop()
"""客戶端建立連線協議物件"""
reactor.connectTCP(HOST, PORT, TSClntFactory())
# """服務端建立連線協議物件"""
# factory = protocol.Factory()
# factory.protocol = TSClntProtocol
# print('客戶端waiting for connection...')
# reactor.listenTCP(PORT, factory)
reactor.run()