Python - 服务器从两个 UDP 套接字监听 [英] Python - Server listening from two UDP sockets

查看:31
本文介绍了Python - 服务器从两个 UDP 套接字监听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.而且我不能让服务器同时监听两个端口.这是我写到现在的代码:

Im new in Python. And I can't make the server listen to two ports at the same time. This is the code I have written until now:

sock_client1 = socket.socket(socket.AF_INET,    # Internet
                     socket.SOCK_DGRAM)         # UDP
sock_client1.bind((SEND_IP, SEND_CLIENT_PORT))
sock_client1.setblocking(0)     

sock_client2 = socket.socket(socket.AF_INET,    # Internet
                     socket.SOCK_DGRAM)         # UDP
sock_client2.bind((SEND_IP, SEND_SERVER_PORT))
sock_client2.setblocking(0)             

while True:
try:

    ready_client1 = select.select([sock_client1], [], [], None)
    ready_client2 = select.select([sock_client2], [], [], None)

    if ready_client1[0]:

        pkt_recv_raw, addr = sock_client1.recvfrom(4096)
        port = SEND_CLIENT_PORT

    if ready_client2[0]:

       pkt_recv_raw, addr = sock_client2.recvfrom(4096)
       port = SEND_SERVER_PORT

当我与客户端一起运行此代码时,服务器无法接收任何内容.当我只使用一个 ready_client 时它才有效.

When I run this code together with a client, the server can't receive anything. It just works when I use only one of the ready_client's.

提前致谢!

推荐答案

ready_client1 = select.select([sock_client1], [], [], None)
ready_client2 = select.select([sock_client2], [], [], None)

尝试使用单个 select:

ready_read, ready_write, exceptional = select.select(
    [sock_client1, sock_client2], [], [], None)


for ready in ready_read:
    pkt_recv_raw, addr = ready.recvfrom(4096)
...

这篇关于Python - 服务器从两个 UDP 套接字监听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆