標籤:
使用twisted搭建socket的伺服器,並能給用戶端發送訊息, 比較簡單,直接上代碼
#coding=utf-8
‘‘‘
用於實現給響應用戶端的請求,並且可以給客戶發送訊息,
‘‘‘
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, Factory
import time
import thread
#線程體,
def timer(no, interval):
while True:
time.sleep(interval)
print(time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time())))
for element in MyFactory.clients:
print(element) #在這裡可以給每個用戶端發送訊息
element.transport.getHandle().sendall(‘dddddddddddd‘)
thread.exit_thread()
class MyProtocal(Protocol):
def connectionMade(self):
self.factory.addClient(self)
def connectionLost(self, reason):
#print(reason)
self.factory.deleteClient(self)
def dataReceived(self, data):
self.transport.write(‘okthis is ok ‘) #在這裡接收使用者的請求認證,並返回資料,發送資料請使用transport.getHandle().sendall() 保證資料立刻發送到用戶端
class MyFactory(Factory):
protocol = MyProtocal
clients=[] #使用者儲存用戶端列表,
def __init__(self):
thread.start_new_thread(timer,(1,3))
#啟動線程用於處理用於給用戶端主動發送資料
def addClient(self, newclient):
print(newclient)
self.clients.append(newclient)
def deleteClient(self, client):
print(client)
self.clients.remove(client)
reactor.listenTCP(9999, MyFactory())
reactor.run()
可以在此基礎上完成很多模組的功能。
存在以下疑惑點,我如何通過代碼來控制停止伺服器。 (如何使用reactor.stop())
python twisted socket 服務端 用戶端