Python socket.recv exception

16,597

That's precisely what a nonblocking socket is supposed to do.

  • Read the available data, if any
  • If nothing is available, raise an error rather than blocking

So you're getting an exception every time you try to receive and there's no data available.

Share:
16,597
Barış Uşaklı
Author by

Barış Uşaklı

Talks to computers all day. Co-Founder of http://nodebb.org GitHub | Twitter

Updated on June 14, 2022

Comments

  • Barış Uşaklı
    Barış Uşaklı almost 2 years

    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.
    

    Obviously an exception is thrown at part = s.recv(4096) but why?