Working with Binary Data in Python
5 stars based on
Sockets are used nearly everywhere, but are one of send binary data udp python most severely misunderstood technologies around. This is a 10, foot overview of sockets. 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. Of the various forms of IPCsockets are by far the most popular.
On any send binary data udp python 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 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.
Roughly speaking, when you clicked on the link that brought you to this page, send binary data udp python browser did something like the following:. 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. 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. A couple things to notice: If we had used s. A second thing to note: 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. More about that later. The send binary data udp python thing to understand now is this: If you need fast IPC between two processes on one machine, you should look into pipes or shared memory. Send binary data udp python most platforms, this will take a shortcut around a couple of layers of network code and be quite a bit faster.
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 connect ing socket starts the conversation, by sending in a request, or perhaps a signon. Now there are two sets of verbs to use for communication. You can use send and recvor you can transform your client socket into a file-like beast and use read and write. The latter is the way Send binary data udp python presents its sockets. Without a send binary data udp python 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 thembecause 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. A protocol like HTTP uses a socket for only one transfer. The client sends a request, then reads a reply. 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. The choice is entirely yours, but some ways are righter send binary data udp python others. 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 recv s - the first to get at least that first character so you can look up the length, send binary data udp python the second in a loop to get the rest. One complication to be aware of: Prefixing the message with its length say, as 5 numeric characters gets more complex, because believe it or notyou may not get all 5 characters in one recv.
And despite having read this, you will eventually get bit by it! In the interests of space, building your character, and preserving my competitive positionthese enhancements are left as an exercise for the reader.
Lets move on to cleaning up. 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, a Motorola chip will represent a 16 bit integer with the value 1 as the two hex bytes 00 Intel and DEC, however, are byte-reversed - send binary data udp python same 1 is 01 Where network order is host order, these do nothing, but where the machine is byte-reversed, these swap the bytes around appropriately.
In these days of 32 bit machines, the ascii representation of binary data is frequently smaller than the binary representation. The shutdown is an advisory to the socket at the other end. Most socket libraries, however, are so used to programmers neglecting to use this piece of etiquette that normally a close is the same as shutdown ; close. So in most situations, an explicit shutdown is not needed.
One way to use shutdown effectively is in an HTTP-like exchange. The client sends a request and then does a shutdown 1. It can assume it has the complete request. The server sends a reply. If the send completes successfully then, indeed, the client was still receiving. But relying on send binary data udp python is a very bad habit. Probably the worst thing about using blocking sockets is what happens when the other side comes down hard without doing a close.
Your socket is likely to hang. TCP is a reliable protocol, and it will wait a long, long time before giving up on a connection. Do not try to kill the thread - part of the reason that threads are more efficient than processes is that they avoid the overhead associated with the automatic recycling of send binary data udp python.
In other words, if you do manage to kill the thread, your whole process is likely to be screwed up. In Python, you use socket. You do this after creating the socket, but before using it. The major mechanical difference is that sendrecvconnect and accept can return without having done anything. You have of course a number of choices. You can check return code and error codes and generally drive yourself crazy. Your app will grow large, buggy and suck CPU.
In C, coding select is fairly complex. You pass select three lists: You should note that a socket can go into more than one list. The select call is blocking, but you can give it a timeout. This is generally a sensible thing to do - give send binary data udp python a nice long timeout say a minute unless you have good reason to do otherwise. In return, you will get three lists. They contain the sockets that are actually readable, send binary data udp python 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 recv on that socket will return something. Same idea for the writable list.
Maybe not all you want to, but something is better than nothing. Actually, any reasonably healthy socket will return as writable - it just means outbound network buffer space is available. If it comes out in the readable list, your accept will almost certainly work. If it shows up in the writable list, you have a decent chance that it has connected.
Actually, select can be handy even with blocking sockets. On Unix, select works both with the sockets and files. Send binary data udp python Windows, send binary data udp python works with sockets only. Also note that in C, many of the more advanced socket options are done differently on Windows. In fact, on Windows I usually use threads which work very, very well with my sockets.
Gordon McMillan Abstract Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around. The Python Software Foundation is a non-profit corporation. Last updated on Apr 09, Created using Sphinx 1.