2010-06-09 117 views
1

我試圖讓使用扭曲的一個簡單的TCP服務器,它可以做向度客戶端之間的相互作用connections.The主代碼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() 

正如意見所如果一個新的客戶端連接到來的時候,我會存儲在一個全局varaible connlist這就好比

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

其連接手柄,並且還分析輸入然後映射其從-在ids信息。然後我檢查是否有中的一把鑰匙個匹配當前「to_id」。如果沒有,獲取連接處理使用connlist[to_id]和推送消息到目標connection.But不work.The消息只顯示在同一connection.Hope有人能告訴我一些有關此方向。

謝謝!

+1

你'dataReceived'函數引用本地'self.connlist',不是全局你最好的朋友。不要使用全局變量。你可能想在康涅狄格州列表存儲在該工廠實例,並通過'self.factory.connlist' – MattH 2010-06-09 11:28:20

+0

從協議實例訪問它@ MattH,謝謝你的note.would你告訴我,我應該存放在'connlist'哪個對象如果我在工廠這樣做? – Young 2010-06-09 12:51:15

+0

如果你能爲這個問題想出一個更好的標題,這將是非常好的事情,這些事情更具體地指出了你想要問的問題。其他人也有類似的問題,這將幫助他們在搜索時找到它。太多太多扭曲的問題題爲「扭曲的問題」或「扭曲的破裂,需要幫助」或「扭曲的幫助」等等。 – Glyph 2010-06-10 07:04:30

回答

3

每次TCP連接時,扭曲將創建TSServerProtocol唯一的實例來處理該連接。所以,你只會在TSServerProtocol中看到1個連接。通常情況下,這是您想要的,但工廠可以擴展以執行您在此嘗試執行的連接跟蹤。具體而言,您可以繼承Factory並覆蓋buildProtocol()方法以跟蹤TSServerProtocol的實例。 Twisted中所有課程之間的相互關係需要一點時間來學習和習慣。尤其是,這塊standard Twisted documentation的應該是接下來將在;-)

+0

謝謝你的好建議。我試圖更好地處理它:) – Young 2010-06-09 13:14:48