Python socket recv until empty

In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:

import sys
import socket
import fcntl, os
import errno
from time import sleep

s = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
s.connect[['127.0.0.1',9999]]
fcntl.fcntl[s, fcntl.F_SETFL, os.O_NONBLOCK]

while True:
    try:
        msg = s.recv[4096]
    except socket.error, e:
        err = e.args[0]
        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
            sleep[1]
            print 'No data available'
            continue
        else:
            # a "real" error occurred
            print e
            sys.exit[1]
    else:
        # got a message, do something :]

The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout[n] or socket.setblocking[False]. In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:

import sys
import socket
from time import sleep

s = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
s.connect[['127.0.0.1',9999]]
s.settimeout[2]

while True:
    try:
        msg = s.recv[4096]
    except socket.timeout, e:
        err = e.args[0]
        # this next if/else is a bit redundant, but illustrates how the
        # timeout exception is setup
        if err == 'timed out':
            sleep[1]
            print 'recv timed out, retry later'
            continue
        else:
            print e
            sys.exit[1]
    except socket.error, e:
        # Something else happened, handle error, exit, etc.
        print e
        sys.exit[1]
    else:
        if len[msg] == 0:
            print 'orderly shutdown on server end'
            sys.exit[0]
        else:
            # got a message do something :]

As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.

See recv[2] and python socket for more details.

Hey everybody.

This is my second project in Python, so please, offer any advice you can, even if it's not related to the question.

I built an ident server in Python, and it works. However, there is an issue with it. Normal ident requests are formatted as "portnumber,portnumber". The server correctly identifies invalid port numbers, too few or too many port numbers, or other malformed requests. If you send the server no data [""] and keep the socket open, however, it will hang at data=fd.recv[1024].strip[] on the recv instruction.

Here is what I have tried so far:

  • Setting a timeout on the socket via settimeout. Result: still hangs, and sends an exception every timeout interval

  • Making the socket non-blocking and using recv loops. I don't know if I'm doing this right, but if I am, the result is: Still hangs, and a ton of exceptions to do with "resource not available"

  • Bashing my head against the wall

  • Making just the recv call non-blocking by using flags. This results in the same thing as #2.

What would you do to fix this? I've been trying to solve this one bug for the past hour and I'm feeling mighty incompetent.

EDIT: Full source code, including the socket muxer I'm using, can be found at //github.com/flotwig/spoofident/

In that code, there is a small test tool called spoofident.test.py which will send arguments to your local ident server and display the response. Running it with no arguments causes the hang I'm speaking of.

Author

Gordon McMillan

Abstract

Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around. This is a 10,000 foot overview of sockets. It’s not really a tutorial - you’ll still have work to do in getting things operational. It doesn’t cover the fine points [and there are a lot of them], but I hope it will give you enough background to begin using them decently.

Sockets¶

I’m only going to talk about INET [i.e. IPv4] sockets, but they account for at least 99% of the sockets in use. And I’ll only talk about STREAM [i.e. TCP] sockets - unless you really know what you’re doing [in which case this HOWTO isn’t for you!], you’ll get better behavior and performance from a STREAM socket than anything else. I will try to clear up the mystery of what a socket is, as well as some hints on how to work with blocking and non-blocking sockets. But I’ll start by talking about blocking sockets. You’ll need to know how they work before dealing with non-blocking sockets.

Part of the trouble with understanding these things is that “socket” can mean a number of subtly different things, depending on context. So first, let’s make a distinction between a “client” socket - an endpoint of a conversation, and a “server” socket, which is more like a switchboard operator. The client application [your browser, for example] uses “client” sockets exclusively; the web server it’s talking to uses both “server” sockets and “client” sockets.

History¶

Of the various forms of IPC, sockets are by far the most popular. On any given platform, there are likely to be other forms of IPC that are faster, but for cross-platform communication, sockets are about the only game in town.

They were invented in Berkeley as part of the BSD flavor of Unix. They spread like wildfire with the internet. With good reason — the combination of sockets with INET makes talking to arbitrary machines around the world unbelievably easy [at least compared to other schemes].

Creating a Socket¶

Roughly speaking, when you clicked on the link that brought you to this page, your browser did something like the following:

# create an INET, STREAMing socket
s = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# now connect to the web server on port 80 - the normal http port
s.connect[["www.python.org", 80]]

When the connect completes, the socket s can be used to send in a request for the text of the page. The same socket will read the reply, and then be destroyed. That’s right, destroyed. Client sockets are normally only used for one exchange [or a small set of sequential exchanges].

What happens in the web server is a bit more complex. First, the web server creates a “server socket”:

# create an INET, STREAMing socket
serversocket = socket.socket[socket.AF_INET, socket.SOCK_STREAM]
# bind the socket to a public host, and a well-known port
serversocket.bind[[socket.gethostname[], 80]]
# become a server socket
serversocket.listen[5]

A couple things to notice: we used socket.gethostname[] so that the socket would be visible to the outside world. If we had used s.bind[['localhost', 80]] or s.bind[['127.0.0.1', 80]] we would still have a “server” socket, but one that was only visible within the same machine. s.bind[['', 80]] specifies that the socket is reachable by any address the machine happens to have.

A second thing to note: low number ports are usually reserved for “well known” services [HTTP, SNMP etc]. If you’re playing around, use a nice high number [4 digits].

Finally, the argument to listen tells the socket library that we want it to queue up as many as 5 connect requests [the normal max] before refusing outside connections. If the rest of the code is written properly, that should be plenty.

Now that we have a “server” socket, listening on port 80, we can enter the mainloop of the web server:

while True:
    # accept connections from outside
    [clientsocket, address] = serversocket.accept[]
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread[clientsocket]
    ct.run[]

There’s actually 3 general ways in which this loop could work - dispatching a thread to handle clientsocket, create a new process to handle clientsocket, or restructure this app to use non-blocking sockets, and multiplex between our “server” socket and any active clientsockets using select. More about that later. The important thing to understand now is this: this is all a “server” socket does. It doesn’t send any data. It doesn’t receive any data. It just produces “client” sockets. Each clientsocket is created in response to some other “client” socket doing a connect[] to the host and port we’re bound to. As soon as we’ve created that clientsocket, we go back to listening for more connections. The two “clients” are free to chat it up - they are using some dynamically allocated port which will be recycled when the conversation ends.

IPC¶

If you need fast IPC between two processes on one machine, you should look into pipes or shared memory. If you do decide to use AF_INET sockets, bind the “server” socket to 'localhost'. On most platforms, this will take a shortcut around a couple of layers of network code and be quite a bit faster.

See also

The multiprocessing integrates cross-platform IPC into a higher-level API.

Using a Socket¶

The first thing to note, is that the web browser’s “client” socket and the web server’s “client” socket are identical beasts. That is, this is a “peer to peer” conversation. Or to put it another way, as the designer, you will have to decide what the rules of etiquette are for a conversation. Normally, the connecting socket starts the conversation, by sending in a request, or perhaps a signon. But that’s a design decision - it’s not a rule of sockets.

Now there are two sets of verbs to use for communication. You can use send and recv, or you can transform your client socket into a file-like beast and use read and write. The latter is the way Java presents its sockets. I’m not going to talk about it here, except to warn you that you need to use flush on sockets. These are buffered “files”, and a common mistake is to write something, and then read for a reply. Without a flush in there, you may wait forever for the reply, because the request may still be in your output buffer.

Now we come to the major stumbling block of sockets - send and recv operate on the network buffers. They do not necessarily handle all the bytes you hand them [or expect from them], because their major focus is handling the network buffers. In general, they return when the associated network buffers have been filled [send] or emptied [recv]. They then tell you how many bytes they handled. It is your responsibility to call them again until your message has been completely dealt with.

When a recv returns 0 bytes, it means the other side has closed [or is in the process of closing] the connection. You will not receive any more data on this connection. Ever. You may be able to send data successfully; I’ll talk more about this later.

A protocol like HTTP uses a socket for only one transfer. The client sends a request, then reads a reply. That’s it. The socket is discarded. This means that a client can detect the end of the reply by receiving 0 bytes.

But if you plan to reuse your socket for further transfers, you need to realize that there is no EOT on a socket. I repeat: if a socket send or recv returns after handling 0 bytes, the connection has been broken. If the connection has not been broken, you may wait on a recv forever, because the socket will not tell you that there’s nothing more to read [for now]. Now if you think about that a bit, you’ll come to realize a fundamental truth of sockets: messages must either be fixed length [yuck], or be delimited [shrug], or indicate how long they are [much better], or end by shutting down the connection. The choice is entirely yours, [but some ways are righter than others].

Assuming you don’t want to end the connection, the simplest solution is a fixed length message:

class MySocket:
    """demonstration class only
      - coded for clarity, not efficiency
    """

    def __init__[self, sock=None]:
        if sock is None:
            self.sock = socket.socket[
                            socket.AF_INET, socket.SOCK_STREAM]
        else:
            self.sock = sock

    def connect[self, host, port]:
        self.sock.connect[[host, port]]

    def mysend[self, msg]:
        totalsent = 0
        while totalsent 

Chủ Đề