【问题标题】:Twisted UDP Server multiple ClientsTwisted UDP Server 多个客户端
【发布时间】:2016-02-14 03:58:04
【问题描述】:

您好,我正在尝试使用twisted 实现一个基本的服务器客户端。我的服务器是一台电脑,客户端是小型嵌入式设备,它们将通过 wifi 通过 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中使用)可以在这里实现吗?

【问题讨论】:

    标签: python sockets udp twisted datagram


    【解决方案1】:

    要在此处获得每 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)
    

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 2012-09-07
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多