簡體   English   中英

Twisted中的TCP服務器問題

[英]Problem with TCP server in Twisted

我正在嘗試使用Twisted創建一個簡單的TCP服務器,該服務器可以在不同的客戶端連接之間進行一些交互。主要代碼如下:

#!/usr/bin/env python
from twisted.internet import protocol, reactor
from time import ctime

#global variables
PORT = 22334
connlist = {}    #store all the connections
ids = {}    #map the from-to relationships

class TSServerProtocol(protocol.Protocol):

    def dataReceived(self, data):
        from_id,to_id = data.split('|') #get the IDs from standard client input,which looks like "from_id|to_id"

        if self.haveConn(from_id):    #try to store new connections' informations
            pass
        else:
            self.setConn(from_id)
            self.setIds(from_id,to_id) 

        if to_id in self.csids.keys():                 
             self.connlist[to_id].transport.write(\
             "you get a message now!from %s \n" % from_id)    #if the to_id target found,push him a message.doesn't work as expected
    def setConn(self,sid):
        connlist[sid] = self

    #some other functions

factory = protocol.Factory()
factory.protocol = TSServerProtocol
print 'waiting from connetction...'
reactor.listenTCP(PORT, factory)
reactor.run()

如評論所述,如果有新的客戶端連接,我會將其連接句柄存儲在全局變量connlist ,就像

connlist = {a_from_id:a_conObj,b_from_id:b_conObj,....}

並且還分析輸入然后映射其從對信息ids 。然后我檢查是否有一個關鍵的ids當前“to_id”。如果沒有,獲取連接處理使用匹配connlist[to_id]並按下一個消息到目標連接。但是它不起作用。該消息僅在同一連接中顯示。希望有人可以向我顯示一些說明。

謝謝!

每次建立TCP連接時,Twisted都會創建一個TSServerProtocol唯一實例來處理該連接。 因此,您只會在TSServerProtocol看到1個連接。 通常,這就是您想要的,但是可以擴展工廠來執行您在此處嘗試進行的連接跟蹤。 具體來說,您可以將Factory子類化,並覆蓋buildProtocol()方法以跟蹤TSServerProtocol實例。 Twisted中所有類之間的相互關系需要一點時間來學習和習慣。 特別是,這個標准的Twisted文檔應該是您下次最好的朋友;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM