使用twisted搭建socket的服務器,並能給客戶端發送消息, 比較簡單,直接上代碼react
#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())app
=========================================
socket
使用reactor.callLater()啓動一個線程.線程裏進行阻塞,或過慮按鈕事件(hook)來調用reactor.stop()
this