Python socket.recv异常

Bar*_*klı 2 python sockets networking

我正在研究一个非常简单的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()
Run Code Online (Sandbox Code Playgroud)

这是客户端一遍又一遍地发送一些数据:

#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) 
Run Code Online (Sandbox Code Playgroud)

我看到服务器一遍又一遍地收到消息"test".但在打印出它收到的内容之前,我收到以下错误消息.

socket.error - A non-blocking socket operation could not be completed immediately.
Run Code Online (Sandbox Code Playgroud)

显然有一个例外,part = s.recv(4096)但为什么呢?

cni*_*tar 8

这正是非阻塞套接字应该做的事情.

  • 阅读可用数据(如果有)
  • 如果没有可用的内容,请返回错误而不是阻止

因此,每次尝试接收时都会收到异常,并且没有可用的数据.

  • 在此链接上也找到了错误代码。10035 不是致命错误,在没有数据接收时抛出。http://msdn.microsoft.com/en-ca/library/windows/desktop/ms740668(v=vs.85).aspx (2认同)