python - 检查python套接字中的数据是否可用

标签 python sockets networking

我想要一个功能来检查数据是否在套接字中等待读取,然后再读取它。这样的事情会有所帮助:

if (data available) then read data

else wait in blocking mode till data becomes available

如何在 Python 中实现这一点

最佳答案

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)

关于python - 检查python套接字中的数据是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23355710/

相关文章:

c++ - 在多线程 HTTP 服务器中发送后如何干净地关闭套接字?

networking - 使用特定地址/接口(interface)拨号?戈朗

hadoop - 在两台不同的计算机上网络连接2个虚拟机

python - 理解 python 中带范围的循环

python - Pandas:根据时间条件将行从一个数据帧映射到另一个数据帧

c++ - 在套接字关闭之前不发送数据

c - 如何从c中的sock结构中获取ip地址?

networking - l3ipvlan(136) 的 IANA ifType 代表什么样的接口(interface)?

python - 如何在 Apache 下使用 Python 3.0?

python - SWIG:从 Python 调用 Go