Python套接字.recv异常
我正在开发一个非常简单的python套接字服务器。我使用非阻塞套接字。服务器和客户机运行在windows 7 x64上,使用python 2.7.3。以下是我从客户端接收数据的代码:Python套接字.recv异常,python,sockets,networking,Python,Sockets,Networking,我正在开发一个非常简单的python套接字服务器。我使用非阻塞套接字。服务器和客户机运行在windows 7 x64上,使用python 2.7.3。以下是我从客户端接收数据的代码: def listenToSockets(self): while True: changed_sockets = self.currentSockets ready_to_read, ready_to_write, in_error = select.select(ch
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()
这是客户端一次又一次地发送一些数据:
#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)
我看到服务器一遍又一遍地接收消息“test”。但在它打印出它收到的内容之前,我得到了以下错误消息
socket.error - A non-blocking socket operation could not be completed immediately.
显然,在
part=s.recv(4096)
上会抛出一个异常,但是为什么呢?这正是非阻塞套接字应该做的
- 读取可用数据(如有)
- 如果没有可用信息,引发错误,而不是阻塞
因此,每次尝试接收时都会出现异常,并且没有可用的数据。在该链接上也找到了错误代码。10035不是致命错误,在没有数据接收时抛出。