[英]How can python socket client receive without being blocked
A simple demo of socket programming in python: 一个简单的python套接字编程演示:
server.py server.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
while True:
data = conn.recv(1024)
print 'Received:', data
if not data:
break
conn.sendall(data)
print 'Sent:', data
conn.close()
client.py client.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
print 'Received:', s.recv(1024)
s.close()
Now code work well. 现在代码运行良好。 However, the client may not know if server will always send back every time. 但是,客户端可能不知道服务器是否每次都会始终发送回。 I tried symmetric code of while-loop in server.py 我在server.py中尝试了while循环的对称代码
client_2.py client_2.py
import socket
host = '127.0.0.1'
port = 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall('Hel')
s.sendall('lo world!')
while True:
data = s.recv(1024)
if not data:
break
print 'Received:', data
s.close()
This code will block at 此代码将在
data = s.recv(1024)
But in server.py, if no data received, it will be blank string, and break from while-loop 但是在server.py中,如果未接收到任何数据,它将为空字符串,并从while循环中断
Why it does not work for client? 为什么它对客户不起作用? How can I do for same functionality without using timeout? 如何在不使用超时的情况下实现相同的功能?
You can set a socket to non-blocking operation via socket.setblocking(false)
, which is equivalent to socket.settimeout(0)
. 您可以通过socket.setblocking(false)
将套接字设置为非阻塞操作,这等效于socket.settimeout(0)
。 Solving this "without using timeout" is impossible. 解决“不使用超时”是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.