Python socket.recv 异常 [英] Python socket.recv exception
问题描述
我正在开发一个非常简单的 python 套接字服务器.我使用非阻塞套接字.服务器和客户端在使用 python 2.7.3 的 windows 7 x64 上运行.这是我从客户端接收数据的代码:
I'm working on a very simple python socket server. I use non-blocking sockets. The server and client are running on windows 7 x64 with python 2.7.3. Here is the code where I receive data from the client :
def listenToSockets(self):
while True:
changed_sockets = self.currentSockets
ready_to_read, ready_to_write, in_error = select.select(changed_sockets,[],[])
for s in ready_to_read:
# if its the server master socket someone is connecting
if s == self.socket:
(client_socket, address) = s.accept()
print "putting " + address[0] + " onto connections\n";
client_socket.setblocking(0)
self.currentSockets.append(client_socket)
print "current client count : " + str(len(self.currentSockets) - 1)
else:
data = ''
try:
while True:
part = s.recv(4096)
if part != '':
data = data + part
elif part == '':
break
except socket.error, (value,message):
print 'socket.error - ' + message
if data != '':
print "server received "+data
else:
print "Disconnected "+str(s.getsockname())
self.currentSockets.remove(s)
s.close()
这里是客户端一遍又一遍地发送一些数据:
And here is the client sending some data over and over again :
#client example
import socket
import time
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('192.168.0.41', 9999))
while 1:
client_socket.send("test")
time.sleep(2)
我看到服务器一遍又一遍地接收消息测试".但在它打印出它收到的内容之前,我收到了以下错误消息.
I see the server receiving the message "test" over and over again. But before it prints out what it received I get the following error message.
socket.error - A non-blocking socket operation could not be completed immediately.
显然在 part = s.recv(4096)
处抛出异常,但为什么呢?
Obviously an exception is thrown at part = s.recv(4096)
but why?
推荐答案
这正是非阻塞套接字应该做的事情.
That's precisely what a nonblocking socket is supposed to do.
- 读取可用数据(如果有)
- 如果没有可用的东西,引发错误而不是阻塞
因此,每次尝试接收时都会遇到异常,但没有可用数据.
So you're getting an exception every time you try to receive and there's no data available.
这篇关于Python socket.recv 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!