扭曲的UDP服务器多个客户端

时间:2015-11-12 17:50:09

标签: python sockets udp twisted datagram

您好我正在尝试使用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中使用)可以在这里实现。

1 个答案:

答案 0 :(得分: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)