我是Python新手。我无法让服务器同时收听两个端口。 这是我到目前为止编写的代码:
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的一个时才起作用。
提前致谢!
答案 0 :(得分:4)
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)
...