465 lines · 20.7 KB · TeX
RawDownload
\documentclass{howto} \title{Socket Programming HOWTO} \release{0.00} \author{Gordon McMillan}\authoraddress{\email{gmcm@hypernet.com}} \begin{document}\maketitle \begin{abstract}\noindentSockets are used nearly everywhere, but are one of the most severelymisunderstood technologies around. This is a 10,000 foot overview ofsockets. It's not really a tutorial - you'll still have work to do ingetting things operational. It doesn't cover the fine points (and thereare a lot of them), but I hope it will give you enough background tobegin using them decently. This document is available from the Python HOWTO page at\url{http://www.python.org/doc/howto}. \end{abstract} \tableofcontents \section{Sockets} Sockets are used nearly everywhere, but are one of the most severelymisunderstood technologies around. This is a 10,000 foot overview ofsockets. It's not really a tutorial - you'll still have work to do ingetting things working. It doesn't cover the fine points (and thereare a lot of them), but I hope it will give you enough background tobegin using them decently. I'm only going to talk about INET sockets, but they account for atleast 99\% of the sockets in use. And I'll only talk about STREAMsockets - unless you really know what you're doing (in which case thisHOWTO isn't for you!), you'll get better behavior and performance froma STREAM socket than anything else. I will try to clear up the mysteryof what a socket is, as well as some hints on how to work withblocking and non-blocking sockets. But I'll start by talking aboutblocking sockets. You'll need to know how they work before dealingwith 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. Sofirst, let's make a distinction between a "client" socket - anendpoint of a conversation, and a "server" socket, which is more likea switchboard operator. The client application (your browser, forexample) uses "client" sockets exclusively; the web server it'stalking to uses both "server" sockets and "client" sockets.  \subsection{History} Of the various forms of IPC (\emph{Inter Process Communication}),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. Theyspread like wildfire with the Internet. With good reason --- thecombination of sockets with INET makes talking to arbitrary machinesaround the world unbelievably easy (at least compared to otherschemes).   \section{Creating a Socket} Roughly speaking, when you clicked on the link that brought you tothis page, your browser did something like the following: \begin{verbatim}    #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.mcmillan-inc.com", 80))\end{verbatim} When the \code{connect} completes, the socket \code{s} cannow be used to send in a request for the text of this page. The samesocket will read the reply, and then be destroyed. That's right -destroyed. Client sockets are normally only used for one exchange (ora small set of sequential exchanges). What happens in the web server is a bit more complex. First, the webserver creates a "server socket". \begin{verbatim}    #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)\end{verbatim} A couple things to notice: we used \code{socket.gethostname()}so that the socket would be visible to the outside world. If we hadused \code{s.bind(('', 80))} or \code{s.bind(('localhost',80))} or \code{s.bind(('127.0.0.1', 80))} we would stillhave a "server" socket, but one that was only visible within the samemachine. A second thing to note: low number ports are usually reserved for"well known" services (HTTP, SNMP etc). If you're playing around, usea nice high number (4 digits). Finally, the argument to \code{listen} tells the socket library thatwe want it to queue up as many as 5 connect requests (the normal max)before refusing outside connections. If the rest of the code iswritten properly, that should be plenty. OK, now we have a "server" socket, listening on port 80. Now we enterthe mainloop of the web server: \begin{verbatim}    while 1:        #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()\end{verbatim} There's actually 3 general ways in which this loop could work -dispatching a thread to handle \code{clientsocket}, create a newprocess to handle \code{clientsocket}, or restructure this appto use non-blocking sockets, and mulitplex between our "server" socketand any active \code{clientsocket}s using\code{select}. More about that later. The important thing tounderstand now is this: this is \emph{all} a "server" socketdoes. It doesn't send any data. It doesn't receive any data. It justproduces "client" sockets. Each \code{clientsocket} is createdin response to some \emph{other} "client" socket doing a\code{connect()} to the host and port we're bound to. As soon aswe've created that \code{clientsocket}, we go back to listeningfor more connections. The two "clients" are free to chat it up - theyare using some dynamically allocated port which will be recycled whenthe conversation ends. \subsection{IPC} If you need fast IPC between two processeson one machine, you should look into whatever form of shared memorythe platform offers. A simple protocol based around shared memory andlocks or semaphores is by far the fastest technique. If you do decide to use sockets, bind the "server" socket to\code{'localhost'}. On most platforms, this will take a shortcutaround a couple of layers of network code and be quite a bit faster.  \section{Using a Socket} The first thing to note, is that the web browser's "client" socket andthe web server's "client" socket are identical beasts. That is, thisis a "peer to peer" conversation. Or to put it another way, \emph{as thedesigner, you will have to decide what the rules of etiquette are fora conversation}. Normally, the \code{connect}ing socketstarts the conversation, by sending in a request, or perhaps asignon. 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\code{send} and \code{recv}, or you can transform yourclient socket into a file-like beast and use \code{read} and\code{write}. The latter is the way Java presents theirsockets. I'm not going to talk about it here, except to warn you thatyou need to use \code{flush} on sockets. These are buffered"files", and a common mistake is to \code{write} something, andthen \code{read} for a reply. Without a \code{flush} inthere, you may wait forever for the reply, because the request maystill be in your output buffer. Now we come the major stumbling block of sockets - \code{send}and \code{recv} operate on the network buffers. They do notnecessarily 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(\code{send}) or emptied (\code{recv}). They then tell youhow many bytes they handled. It is \emph{your} responsibility to callthem again until your message has been completely dealt with. When a \code{recv} returns 0 bytes, it means the other side hasclosed (or is in the process of closing) the connection.  You will notreceive any more data on this connection. Ever.  You may be able tosend data successfully; I'll talk about that some on the next page. A protocol like HTTP uses a socket for only one transfer. The clientsends a request, the reads a reply.  That's it. The socket isdiscarded. This means that a client can detect the end of the reply byreceiving 0 bytes. But if you plan to reuse your socket for further transfers, you needto realize that \emph{there is no "EOT" (End of Transfer) on asocket.} I repeat: if a socket \code{send} or\code{recv} returns after handling 0 bytes, the connection hasbeen broken.  If the connection has \emph{not} been broken, you maywait on a \code{recv} forever, because the socket will\emph{not} tell you that there's nothing more to read (for now).  Nowif you think about that a bit, you'll come to realize a fundamentaltruth of sockets: \emph{messages must either be fixed length} (yuck),\emph{or be delimited} (shrug), \emph{or indicate how long they are}(much better), \emph{or end by shutting down the connection}. Thechoice is entirely yours, (but some ways are righter than others). Assuming you don't want to end the connection, the simplest solutionis a fixed length message: \begin{verbatim}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):	msg = ''	while len(msg) < MSGLEN:	    chunk = self.sock.recv(MSGLEN-len(msg))	    if chunk == '':		raise RuntimeError, \\		    "socket connection broken"	    msg = msg + chunk	return msg\end{verbatim} The sending code here is usable for almost any messaging scheme - inPython you send strings, and you can use \code{len()} todetermine its length (even if it has embedded \code{\e 0}characters). It's mostly the receiving code that gets morecomplex. (And in C, it's not much worse, except you can't use\code{strlen} if the message has embedded \code{\e 0}s.) The easiest enhancement is to make the first character of the messagean indicator of message type, and have the type determine thelength. Now you have two \code{recv}s - the first to get (atleast) that first character so you can look up the length, and thesecond in a loop to get the rest. If you decide to go the delimitedroute, you'll be receiving in some arbitrary chunk size, (4096 or 8192is frequently a good match for network buffer sizes), and scanningwhat you've received for a delimiter. One complication to be aware of: if your conversational protocolallows multiple messages to be sent back to back (without some kind ofreply), and you pass \code{recv} an arbitrary chunk size, youmay end up reading the start of a following message. You'll need toput that aside and hold onto it, until it's needed. Prefixing the message with it's length (say, as 5 numeric characters)gets more complex, because (believe it or not), you may not get all 5characters in one \code{recv}. In playing around, you'll getaway with it; but in high network loads, your code will very quicklybreak unless you use two \code{recv} loops - the first todetermine the length, the second to get the data part of themessage. Nasty. This is also when you'll discover that\code{send} does not always manage to get rid of everything inone pass. And despite having read this, you will eventually get bit byit! In the interests of space, building your character, (and preserving mycompetitive position), these enhancements are left as an exercise forthe reader. Lets move on to cleaning up. \subsection{Binary Data} It is perfectly possible to send binary data over a socket. The majorproblem is that not all machines use the same formats for binarydata. For example, a Motorola chip will represent a 16 bit integerwith the value 1 as the two hex bytes 00 01. Intel and DEC, however,are byte-reversed - that same 1 is 01 00. Socket libraries have callsfor converting 16 and 32 bit integers - \code{ntohl, htonl, ntohs,htons} where "n" means \emph{network} and "h" means \emph{host},"s" means \emph{short} and "l" means \emph{long}. Where network orderis host order, these do nothing, but where the machine isbyte-reversed, these swap the bytes around appropriately. In these days of 32 bit machines, the ascii representation of binarydata is frequently smaller than the binary representation. That'sbecause a surprising amount of the time, all those longs have thevalue 0, or maybe 1. The string "0" would be two bytes, while binaryis four. Of course, this doesn't fit well with fixed-lengthmessages. Decisions, decisions. \section{Disconnecting} Strictly speaking, you're supposed to use \code{shutdown} on asocket before you \code{close} it.  The \code{shutdown} isan advisory to the socket at the other end.  Depending on the argumentyou pass it, it can mean "I'm not going to send anymore, but I'llstill listen", or "I'm not listening, good riddance!".  Most socketlibraries, however, are so used to programmers neglecting to use thispiece of etiquette that normally a \code{close} is the same as\code{shutdown(); close()}.  So in most situations, an explicit\code{shutdown} is not needed. One way to use \code{shutdown} effectively is in an HTTP-likeexchange. The client sends a request and then does a\code{shutdown(1)}. This tells the server "This client is donesending, but can still receive."  The server can detect "EOF" by areceive of 0 bytes. It can assume it has the complete request.  Theserver sends a reply. If the \code{send} completes successfullythen, indeed, the client was still receiving. Python takes the automatic shutdown a step further, and says that when a socket is garbage collected, it will automatically do a \code{close} if it's needed. But relying on this is a very bad habit. If your socket just disappears without doing a \code{close}, the socket at the other end may hang indefinitely, thinking you're just being slow. \emph{Please} \code{close} your sockets when you're done.  \subsection{When Sockets Die} Probably the worst thing about using blocking sockets is what happenswhen the other side comes down hard (without doing a\code{close}). Your socket is likely to hang. SOCKSTREAM is areliable protocol, and it will wait a long, long time before giving upon a connection. If you're using threads, the entire thread isessentially dead. There's not much you can do about it. As long as youaren't doing something dumb, like holding a lock while doing ablocking read, the thread isn't really consuming much in the way ofresources. Do \emph{not} try to kill the thread - part of the reasonthat threads are more efficient than processes is that they avoid theoverhead associated with the automatic recycling of resources. Inother words, if you do manage to kill the thread, your whole processis likely to be screwed up.   \section{Non-blocking Sockets} If you've understood the preceeding, you already know most of what youneed to know about the mechanics of using sockets. You'll still usethe same calls, in much the same ways. It's just that, if you do itright, your app will be almost inside-out. In Python, you use \code{socket.setblocking(0)} to make itnon-blocking. In C, it's more complex, (for one thing, you'll need tochoose between the BSD flavor \code{O_NONBLOCK} and the almostindistinguishable Posix flavor \code{O_NDELAY}, which iscompletely different from \code{TCP_NODELAY}), but it's theexact same idea. You do this after creating the socket, but beforeusing it. (Actually, if you're nuts, you can switch back and forth.) The major mechanical difference is that \code{send},\code{recv}, \code{connect} and \code{accept} canreturn without having done anything. You have (of course) a number ofchoices. You can check return code and error codes and generally driveyourself crazy. If you don't believe me, try it sometime. Your appwill grow large, buggy and suck CPU. So let's skip the brain-deadsolutions and do it right. Use \code{select}. In C, coding \code{select} is fairly complex. In Python, it's apiece of cake, but it's close enough to the C version that if youunderstand \code{select} in Python, you'll have little troublewith it in C. \begin{verbatim}    ready_to_read, ready_to_write, in_error = \\                   select.select(                      potential_readers,                       potential_writers,                       potential_errs,                       timeout)\end{verbatim} You pass \code{select} three lists: the first contains allsockets that you might want to try reading; the second all the socketsyou might want to try writing to, and the last (normally left empty)those that you want to check for errors.  You should note that asocket can go into more than one list. The \code{select} call isblocking, but you can give it a timeout. This is generally a sensiblething to do - give it a nice long timeout (say a minute) unless youhave good reason to do otherwise. In return, you will get three lists. They have the sockets that areactually readable, writable and in error. Each of these lists is asubset (possbily empty) of the corresponding list you passed in. Andif you put a socket in more than one input list, it will only be (atmost) in one output list. If a socket is in the output readable list, you can beas-close-to-certain-as-we-ever-get-in-this-business that a\code{recv} on that socket will return \emph{something}. Sameidea for the writable list. You'll be able to send\emph{something}. Maybe not all you want to, but \emph{something} isbetter than nothing. (Actually, any reasonably healthy socket willreturn as writable - it just means outbound network buffer space isavailable.) If you have a "server" socket, put it in the potential_readerslist. If it comes out in the readable list, your \code{accept}will (almost certainly) work. If you have created a new socket to\code{connect} to someone else, put it in the ptoential_writerslist. If it shows up in the writable list, you have a decent chancethat it has connected. One very nasty problem with \code{select}: if somewhere in thoseinput lists of sockets is one which has died a nasty death, the\code{select} will fail. You then need to loop through everysingle damn socket in all those lists and do a\code{select([sock],[],[],0)} until you find the bad one. Thattimeout of 0 means it won't take long, but it's ugly. Actually, \code{select} can be handy even with blocking sockets.It's one way of determining whether you will block - the socketreturns as readable when there's something in the buffers.  However,this still doesn't help with the problem of determining whether theother end is done, or just busy with something else. \textbf{Portability alert}: On Unix, \code{select} works both withthe sockets and files. Don't try this on Windows. On Windows,\code{select} works with sockets only. Also note that in C, manyof the more advanced socket options are done differently onWindows. In fact, on Windows I usually use threads (which work very,very well) with my sockets. Face it, if you want any kind ofperformance, your code will look very different on Windows than onUnix. (I haven't the foggiest how you do this stuff on a Mac.) \subsection{Performance} There's no question that the fastest sockets code uses non-blockingsockets and select to multiplex them. You can put together somethingthat will saturate a LAN connection without putting any strain on theCPU. The trouble is that an app written this way can't do much ofanything else - it needs to be ready to shuffle bytes around at alltimes. Assuming that your app is actually supposed to do something more thanthat, threading is the optimal solution, (and using non-blockingsockets will be faster than using blocking sockets). Unfortunately,threading support in Unixes varies both in API and quality. So thenormal Unix solution is to fork a subprocess to deal with eachconnection. The overhead for this is significant (and don't do this onWindows - the overhead of process creation is enormous there). It alsomeans that unless each subprocess is completely independent, you'llneed to use another form of IPC, say a pipe, or shared memory andsemaphores, to communicate between the parent and child processes. Finally, remember that even though blocking sockets are somewhatslower than non-blocking, in many cases they are the "right"solution. After all, if your app is driven by the data it receivesover a socket, there's not much sense in complicating the logic justso your app can wait on \code{select} instead of\code{recv}. \end{document}