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: Show
The situation is a little different in the case where you've enabled non-blocking behavior via a time out with
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:
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 https://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. 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 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 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 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 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 See also The 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 Now there are two sets of verbs to use for communication. You can
use Now we come to the major stumbling block of sockets - When a 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 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 < MSGLEN: sent = self.sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent = totalsent + sent def myreceive(self): chunks = [] bytes_recd = 0 while bytes_recd < MSGLEN: chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048)) if chunk == b'': raise RuntimeError("socket connection broken") chunks.append(chunk) bytes_recd = bytes_recd + len(chunk) return b''.join(chunks) The sending code here is usable for almost
any messaging scheme - in Python you send strings, and you can use The easiest enhancement is to make the first character of the message an indicator of message type, and have the type determine the length. Now you have two One complication to be aware of: if your conversational protocol allows multiple messages to be sent back to back (without some kind of reply), and you pass Prefixing the message with its length (say, as 5 numeric characters) gets more complex, because (believe it or not), you may not get all 5 characters in one In the interests of space, building your character, (and preserving my competitive position), these enhancements are left as an exercise for the reader. Lets move on to cleaning up. Binary Data¶It is perfectly possible to send binary data over a socket. The major problem is that not all machines use the same formats for binary data. For example, network byte order is big-endian, with the most significant byte first, so a 16 bit integer with the value Socket libraries have calls for converting 16 and 32 bit integers - In these days of 64-bit machines, the ASCII representation of binary data is frequently smaller than the binary representation. That’s because a surprising amount of the time, most integers have the value 0, or maybe 1. The string Disconnecting¶Strictly speaking, you’re supposed to use One way to use Python takes the automatic shutdown a step further, and says that when a socket is garbage collected, it will automatically do a When Sockets Die¶Probably the worst thing about using blocking sockets is what happens when the other side comes down hard (without doing a Non-blocking Sockets¶If you’ve understood the preceding, you already know most of what you need to know about the mechanics of using sockets. You’ll still use the same calls, in much the same ways. It’s just that, if you do it right, your app will be almost inside-out. In Python, you use The major mechanical difference is that Use In C, coding ready_to_read, ready_to_write, in_error = \ select.select( potential_readers, potential_writers, potential_errs, timeout) You pass
In return, you will get three lists. They contain the sockets that are actually readable, writable and in error. Each of these lists is a subset (possibly empty) of the corresponding list you passed in. If a socket is in the output readable list, you can be as-close-to-certain-as-we-ever-get-in-this-business that a If you have a “server” socket, put it in the potential_readers list. If it comes out in the readable list, your Actually, Portability alert: On Unix, What does recv () return in python?The recv() call receives data on a socket with descriptor socket and stores it in a buffer. The recv() call applies only to connected sockets. This call returns the length of the incoming message or data. If a datagram packet is too long to fit in the supplied buffer, datagram sockets discard excess bytes.
What does socket recv do python?The recv method receives up to buffersize bytes from the socket. When no data is available, it blocks until at least one byte is available or until the remote end is closed. When the remote end is closed and all data is read, it returns an empty byte string.
How do you use a nonIn Python, you use socket. setblocking(False) to make it non-blocking.
What is sendall in python?sendall is a high-level Python-only method that sends the entire buffer you pass or throws an exception. It does that by calling socket. send until everything has been sent or an error occurs.
|