Socket Programming HOWTO

Author:

Gordon McMillan

Abstract

Sockets are used nearly everywhere, but are one of the most severelymisunderstood 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 thingsoperational. It doesn’t cover the fine points (and there are a lot of them), butI 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% ofthe sockets in use. And I’ll only talk about STREAM (i.e. TCP) sockets - unless you reallyknow what you’re doing (in which case this HOWTO isn’t for you!), you’ll getbetter behavior and performance from a STREAM socket than anything else. I willtry to clear up the mystery of what a socket is, as well as some hints on how towork with blocking and non-blocking sockets. But I’ll start by talking aboutblocking sockets. You’ll need to know how they work before dealing withnon-blocking sockets.

Part of the trouble with understanding these things is that «socket» can mean anumber of subtly different things, depending on context. So first, let’s make adistinction between a «client» socket - an endpoint of a conversation, and a«server» socket, which is more like a switchboard operator. The clientapplication (your browser, for example) uses «client» sockets exclusively; theweb server it’s talking to uses both «server» sockets and «client» sockets.

History

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

They were invented in Berkeley as part of the BSD flavor of Unix. They spreadlike wildfire with the internet. With good reason — the combination of socketswith 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 sockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM)# now connect to the web server on port 80 - the normal http ports.connect(("www.python.org",80))

When theconnect completes, the sockets can be used to sendin a request for the text of the page. The same socket will read thereply, and then be destroyed. That’s right, destroyed. Client socketsare normally only used for one exchange (or a small set of sequentialexchanges).

What happens in the web server is a bit more complex. First, the web servercreates a «server socket»:

# create an INET, STREAMing socketserversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)# bind the socket to a public host, and a well-known portserversocket.bind((socket.gethostname(),80))# become a server socketserversocket.listen(5)

A couple things to notice: we usedsocket.gethostname() so that the socketwould be visible to the outside world. If we had useds.bind(('localhost',80)) ors.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 tohave.

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 (4digits).

Finally, the argument tolisten tells the socket library that we want it toqueue up as many as 5 connect requests (the normal max) before refusing outsideconnections. 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 themainloop of the web server:

whileTrue:# accept connections from outside(clientsocket,address)=serversocket.accept()# now do something with the clientsocket# in this case, we'll pretend this is a threaded serverct=make_client_thread(clientsocket)ct.start()

There’s actually 3 general ways in which this loop could work - dispatching athread to handleclientsocket, create a new process to handleclientsocket, or restructure this app to use non-blocking sockets, andmultiplex between our «server» socket and any activeclientsockets usingselect. More about that later. The important thing to understand now isthis: this isall a «server» socket does. It doesn’t send any data. It doesn’treceive any data. It just produces «client» sockets. Eachclientsocket iscreated in response to someother «client» socket doing aconnect() to thehost and port we’re bound to. As soon as we’ve created thatclientsocket, wego back to listening for more connections. The two «clients» are free to chat itup - they are using some dynamically allocated port which will be recycled whenthe conversation ends.

IPC

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

Δείτε επίσης

Themultiprocessing integrates cross-platform IPC into a higher-levelAPI.

Using a Socket

The first thing to note, is that the web browser’s «client» socket and the webserver’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 todecide what the rules of etiquette are for a conversation. Normally, theconnecting socket starts the conversation, by sending in a request, orperhaps 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 usesendandrecv, or you can transform your client socket into a file-like beast anduseread andwrite. 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 useflush on sockets. These are buffered «files», and a common mistake is towrite something, and thenread for a reply. Without aflush inthere, you may wait forever for the reply, because the request may still be inyour output buffer.

Now we come to the major stumbling block of sockets -send andrecv operateon the network buffers. They do not necessarily handle all the bytes you handthem (or expect from them), because their major focus is handling the networkbuffers. In general, they return when the associated network buffers have beenfilled (send) or emptied (recv). They then tell you how many bytes theyhandled. It isyour responsibility to call them again until your message hasbeen completely dealt with.

When arecv returns 0 bytes, it means the other side has closed (or is inthe process of closing) the connection. You will not receive any more data onthis connection. Ever. You may be able to send data successfully; I’ll talkmore about this later.

A protocol like HTTP uses a socket for only one transfer. The client sends arequest, then reads a reply. That’s it. The socket is discarded. This means thata 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 realizethatthere is noEOTon a socket. I repeat: if a socketsend orrecv returns after handling 0 bytes, the connection has beenbroken. If the connection hasnot been broken, you may wait on arecvforever, because the socket willnot tell you that there’s nothing more toread (for now). Now if you think about that a bit, you’ll come to realize afundamental truth of sockets:messages must either be fixed length (yuck),orbe delimited (shrug),or indicate how long they are (much better),or end byshutting down the connection. The choice is entirely yours, (but some ways arerighter than others).

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

The sending code here is usable for almost any messaging scheme - in Python yousend strings, and you can uselen() to determine its length (even if it hasembedded\0 characters). It’s mostly the receiving code that gets morecomplex. (And in C, it’s not much worse, except you can’t usestrlen if themessage has embedded\0s.)

The easiest enhancement is to make the first character of the message anindicator of message type, and have the type determine the length. Now you havetworecvs - the first to get (at least) that first character so you canlook up the length, and the second in a loop to get the rest. If you decide togo the delimited route, you’ll be receiving in some arbitrary chunk size, (4096or 8192 is frequently a good match for network buffer sizes), and scanning whatyou’ve received for a delimiter.

One complication to be aware of: if your conversational protocol allows multiplemessages to be sent back to back (without some kind of reply), and you passrecv an arbitrary chunk size, you may end up reading the start of afollowing message. You’ll need to put that aside and hold onto it, until it’sneeded.

Prefixing the message with its length (say, as 5 numeric characters) gets morecomplex, because (believe it or not), you may not get all 5 characters in onerecv. In playing around, you’ll get away with it; but in high network loads,your code will very quickly break unless you use tworecv loops - the firstto determine the length, the second to get the data part of the message. Nasty.This is also when you’ll discover thatsend does not always manage to getrid of everything in one pass. And despite having read this, you will eventuallyget bit by it!

In the interests of space, building your character, (and preserving mycompetitive position), these enhancements are left as an exercise for thereader. Lets move on to cleaning up.

Binary Data

It is perfectly possible to send binary data over a socket. The major problem isthat not all machines use the same formats for binary data. For example,network byte orderis big-endian, with the most significant byte first,so a 16 bit integer with the value1 would be the two hex bytes0001.However, most common processors (x86/AMD64, ARM, RISC-V), are little-endian,with the least significant byte first - that same1 would be0100.

Socket libraries have calls for converting 16 and 32 bit integers -ntohl,htonl,ntohs,htons where «n» meansnetwork and «h» meanshost, «s» meansshort and «l» meanslong. Where network order is host order, these donothing, but where the machine is byte-reversed, these swap the bytes aroundappropriately.

In these days of 64-bit machines, the ASCII representation of binary data isfrequently smaller than the binary representation. That’s because a surprisingamount of the time, most integers have the value 0, or maybe 1.The string"0" would be two bytes, while a full 64-bit integer would be 8.Of course, this doesn’t fit well with fixed-length messages.Decisions, decisions.

Disconnecting

Strictly speaking, you’re supposed to useshutdown on a socket before youclose it. Theshutdown is an advisory to the socket at the other end.Depending on the argument you pass it, it can mean «I’m not going to sendanymore, but I’ll still listen», or «I’m not listening, good riddance!». Mostsocket libraries, however, are so used to programmers neglecting to use thispiece of etiquette that normally aclose is the same asshutdown();close(). So in most situations, an explicitshutdown is not needed.

One way to useshutdown effectively is in an HTTP-like exchange. The clientsends a request and then does ashutdown(1). This tells the server «Thisclient is done sending, but can still receive.» The server can detect «EOF» bya receive of 0 bytes. It can assume it has the complete request. The serversends a reply. If thesend completes successfully then, indeed, the clientwas still receiving.

Python takes the automatic shutdown a step further, and says that when a socketis garbage collected, it will automatically do aclose if it’s needed. Butrelying on this is a very bad habit. If your socket just disappears withoutdoing aclose, the socket at the other end may hang indefinitely, thinkingyou’re just being slow.Pleaseclose your sockets when you’re done.

When Sockets Die

Probably the worst thing about using blocking sockets is what happens when theother side comes down hard (without doing aclose). Your socket is likely tohang. TCP is a reliable protocol, and it will wait a long, long timebefore giving up on a connection. If you’re using threads, the entire thread isessentially dead. There’s not much you can do about it. As long as you aren’tdoing something dumb, like holding a lock while doing a blocking read, thethread isn’t really consuming much in the way of resources. Donot try to killthe thread - part of the reason that threads are more efficient than processesis that they avoid the overhead associated with the automatic recycling ofresources. In other words, if you do manage to kill the thread, your wholeprocess is likely to be screwed up.

Non-blocking Sockets

If you’ve understood the preceding, you already know most of what you need toknow about the mechanics of using sockets. You’ll still use the same calls, inmuch the same ways. It’s just that, if you do it right, your app will be almostinside-out.

In Python, you usesocket.setblocking(False) to make it non-blocking. In C, it’smore complex, (for one thing, you’ll need to choose between the BSD flavorO_NONBLOCK and the almost indistinguishable POSIX flavorO_NDELAY, whichis completely different fromTCP_NODELAY), but it’s the exact same idea. Youdo this after creating the socket, but before using it. (Actually, if you’renuts, you can switch back and forth.)

The major mechanical difference is thatsend,recv,connect andaccept can return without having done anything. You have (of course) anumber of choices. You can check return code and error codes and generally driveyourself crazy. If you don’t believe me, try it sometime. Your app will growlarge, buggy and suck CPU. So let’s skip the brain-dead solutions and do itright.

Useselect.

In C, codingselect is fairly complex. In Python, it’s a piece of cake, butit’s close enough to the C version that if you understandselect in Python,you’ll have little trouble with it in C:

ready_to_read,ready_to_write,in_error= \select.select(potential_readers,potential_writers,potential_errs,timeout)

You passselect three lists: the first contains all sockets that you mightwant to try reading; the second all the sockets you might want to try writingto, and the last (normally left empty) those that you want to check for errors.You should note that a socket can go into more than one list. Theselectcall is blocking, but you can give it a timeout. This is generally a sensiblething to do - give it a nice long timeout (say a minute) unless you have goodreason to do otherwise.

In return, you will get three lists. They contain the sockets that are actuallyreadable, writable and in error. Each of these lists is a subset (possiblyempty) of the corresponding list you passed in.

If a socket is in the output readable list, you can beas-close-to-certain-as-we-ever-get-in-this-business that arecv on thatsocket will returnsomething. Same idea for the writable list. You’ll be ableto sendsomething. Maybe not all you want to, butsomething is better thannothing. (Actually, any reasonably healthy socket will return as writable - itjust means outbound network buffer space is available.)

If you have a «server» socket, put it in the potential_readers list. If it comesout in the readable list, youraccept will (almost certainly) work. If youhave created a new socket toconnect to someone else, put it in thepotential_writers list. If it shows up in the writable list, you have a decentchance that it has connected.

Actually,select can be handy even with blocking sockets. It’s one way ofdetermining whether you will block - the socket returns as readable when there’ssomething in the buffers. However, this still doesn’t help with the problem ofdetermining whether the other end is done, or just busy with something else.

Portability alert: On Unix,select works both with the sockets andfiles. Don’t try this on Windows. On Windows,select works with socketsonly. Also note that in C, many of the more advanced socket options are donedifferently on Windows. In fact, on Windows I usually use threads (which workvery, very well) with my sockets.