2015-11-12 97 views
1

嗨我試圖實現一個基本的服務器客戶端使用扭曲。我的服務器是一臺PC,客戶端是小型嵌入式設備,它將通過無線網絡通過UDP進行通信。下面是我使用的例子扭曲的UDP服務器多個客戶端

from twisted.internet.protocol import DatagramProtocol 
from twisted.internet import protocol, reactor 
import time 
from socket import SOL_SOCKET, SO_BROADCAST 

class Echo(protocol.DatagramProtocol): 
    def datagramReceived(self, data, (host, port)): 
     while(1): 
      self.transport.write(data, (host, port)) 
      ##Recieve Some thing here on the current ip 
      ##Perform some task have to send and recieve couple of 
      ##times 
      time.sleep(3) 

    def main(): 

     reactor.listenUDP(8000, Echo()) 
     reactor.run() 
     print 'Reactor running\n' 
     #protocol.startProtocol() 
     while(1): 
      command_input = input("Enter your Command ") 
      if command_input == exit: 
       print 'Exiting' 
       exit() 

if __name__ == '__main__': 
    main() 

我會從客戶端接收數據包,然後我將有一些數據發送回一個非常小的實現,然後再客戶端會發送一些數據,這將繼續對一些而。有什麼辦法可以在datagramRecieved()函數中做到這一點,並同時爲其他客戶端服務。在這個實現中,一旦調用datagramRecieved()函數,我無法收到其他任何東西,直到它返回。有一個工廠的概念(我認爲在tcp中使用)可以在這裏實現。

回答

0

要在這裏發送每3秒發送一個數據包的效果,您需要使用LoopingCall。實際上,如果你的sleep像你的例子那樣,根據各種緩衝區的大小,你可能根本不會發送這些數據包,直到你回到反應堆;寫入事件就像讀取一樣。

如何可能的工作的一個例子:

from twisted.internet import protocol, task 
class Echo(protocol.DatagramProtocol): 
    def datagramReceived(self, data, (host, port)): 
     def reply(): 
      self.transport.write(data, (host, port)) 
     task.LoopingCall(reply).start(3.0)