简体   繁体   English

使用Select的Python套接字检查数据

[英]Python Socket Using Select To Check For Data

I found the following code on another post that works pretty good: 我在另一篇不错的文章中找到了以下代码:

UDP_IP = ''
UDP_PORT = 5008
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', UDP_PORT))
while 1:
  socket_list = [sys.stdin, s]
  # Get the list sockets which are readable
  read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
  for sock in read_sockets:
   #incoming message from remote server
   if sock == s:
      data = sock.recv(4096)
      if not data :
        print '\nDisconnected from server'
        sys.exit()
      else :
         #print data
         sys.stdout.write(data)

   #user entered a message
   else :
     msg = sys.stdin.readline()
     s.send(msg)

The problem I've got is with the for loop since it only runs through it when there is data received. 我遇到的问题是for循环,因为它仅在收到数据时才通过它运行。 I would really like it to use a while loop and have it occasionally check on if data has been received but I can't figure out how to do this. 我真的希望它使用while循环,并偶尔检查是否已接收到数据,但是我不知道该怎么做。

Use the timeout parameter in the select statement. 在select语句中使用timeout参数。 If no data is available (indicated by empty lists), you can do whatever other processing is needed in the body of the while loop. 如果没有可用数据(由空列表指示),则可以执行while循环主体中需要进行的其他任何处理。

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

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