python twisted socket 服務端 用戶端

來源:互聯網
上載者:User

標籤:

使用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 服務端 用戶端

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.