简体   繁体   English

Python通过套接字接收数据并通过Web套接字转发数据

[英]Python receiving data via socket and forwarding it via web socket

Being completely new to web sockets and relatively new to Python, I was wondering if it is possible to write a server (or if one already exists, that would be even better) in Python that receives data via a standard socket (UDP) and forwards that data via web sockets to a browser? 对于Web套接字来说是全新的,而对Python而言则相对较新,我想知道是否可以在Python中编写通过标准套接字(UDP)接收数据并转发的服务器(或者如果已经存在,那会更好)。通过网络套接字到浏览器的数据? I notice in using Tornado, that the last line of your main is typically: 我在使用Tornado时注意到,您的主线通常是:

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

Which creates a "listener" loop and would seem to prevent me from receiving any data on my standard socket. 这会创建一个“监听器”循环,并且似乎阻止了我在标准套接字上接收任何数据。 Is it possible to do this? 是否有可能做到这一点?

Tornado doesn't have any explicit APIs for dealing with UDP, but you can add a UDP socket with IOLoop.add_handler (the following code is untested but should give you the basic idea): Tornado没有用于处理UDP的任何显式API,但是您可以使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM