我正在研究一个非常简单的python套接字服务器。我使用非阻塞套接字。服务器和客户端在带有python 2.7.3的Windows 7 x64上运行。这是我从客户端接收数据的代码:
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)
会引发异常,但为什么?
答案 0 :(得分:8)
这正是非阻塞套接字应该做的事情。
因此,每次尝试接收时都会收到异常,并且没有可用的数据。