2015-09-07 82 views
0

对于网络套接字和Python相对来说比较新的,我一直在想是否可以编写一个服务器(或者如果已经存在,那会更好)在Python中通过标准套接字(UDP)接收数据并通过Web套接字将数据转发给浏览器?我注意到在使用龙卷风,你的主要的最后一行通常是:Python通过套接字接收数据并通过网络套接字转发它

tornado.ioloop.IOLoop.instance().start() 

它创建了一个“听众”循环,似乎阻止我接受对我的标准插孔的任何数据。是否有可能做到这一点?

回答

1

龙卷风没有任何明确的API来处理UDP,但您可以用IOLoop.add_handler添加一个UDP套接字(下面的代码是未经测试,但应该给你的基本概念):

def handle_udp(sock, events): 
    while True: 
     try: 
      data, addr = sock.recvfrom(bufsize) 
      # do stuff with data 
     except socket.error as e: 
      if e.errno in (errno.EAGAIN, errno.WOULDBLOCK): 
       # nothing more to read, return to the IOLoop 
       return 

sock = bind_udp_socket() 
sock.setblocking(0) 
IOLoop.current().add_handler(sock, IOLoop.READ) 
IOLoop.current().start() 
相关问题