blob: 0607a933b4d559a892906ee1ee85b67a3a5b571a [file] [log] [blame]
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +00001\documentclass{howto}
2
3\title{Socket Programming HOWTO}
4
5\release{0.00}
6
7\author{Gordon McMillan}
8\authoraddress{\email{gmcm@hypernet.com}}
9
10\begin{document}
11\maketitle
12
13\begin{abstract}
14\noindent
15Sockets are used nearly everywhere, but are one of the most severely
16misunderstood technologies around. This is a 10,000 foot overview of
17sockets. It's not really a tutorial - you'll still have work to do in
18getting things operational. It doesn't cover the fine points (and there
19are a lot of them), but I hope it will give you enough background to
20begin using them decently.
21
22This document is available from the Python HOWTO page at
23\url{http://www.python.org/doc/howto}.
24
25\end{abstract}
26
27\tableofcontents
28
29\section{Sockets}
30
31Sockets are used nearly everywhere, but are one of the most severely
32misunderstood technologies around. This is a 10,000 foot overview of
33sockets. It's not really a tutorial - you'll still have work to do in
34getting things working. It doesn't cover the fine points (and there
35are a lot of them), but I hope it will give you enough background to
36begin using them decently.
37
38I'm only going to talk about INET sockets, but they account for at
39least 99\% of the sockets in use. And I'll only talk about STREAM
40sockets - unless you really know what you're doing (in which case this
41HOWTO isn't for you!), you'll get better behavior and performance from
42a STREAM socket than anything else. I will try to clear up the mystery
43of what a socket is, as well as some hints on how to work with
44blocking and non-blocking sockets. But I'll start by talking about
45blocking sockets. You'll need to know how they work before dealing
46with non-blocking sockets.
47
48Part of the trouble with understanding these things is that "socket"
49can mean a number of subtly different things, depending on context. So
50first, let's make a distinction between a "client" socket - an
51endpoint of a conversation, and a "server" socket, which is more like
52a switchboard operator. The client application (your browser, for
53example) uses "client" sockets exclusively; the web server it's
54talking to uses both "server" sockets and "client" sockets.
55
56
57\subsection{History}
58
59Of the various forms of IPC (\emph{Inter Process Communication}),
60sockets are by far the most popular. On any given platform, there are
61likely to be other forms of IPC that are faster, but for
62cross-platform communication, sockets are about the only game in town.
63
64They were invented in Berkeley as part of the BSD flavor of Unix. They
65spread like wildfire with the Internet. With good reason --- the
66combination of sockets with INET makes talking to arbitrary machines
67around the world unbelievably easy (at least compared to other
68schemes).
69
70\section{Creating a Socket}
71
72Roughly speaking, when you clicked on the link that brought you to
73this page, your browser did something like the following:
74
75\begin{verbatim}
76 #create an INET, STREAMing socket
77 s = socket.socket(
78 socket.AF_INET, socket.SOCK_STREAM)
79 #now connect to the web server on port 80
80 # - the normal http port
81 s.connect(("www.mcmillan-inc.com", 80))
82\end{verbatim}
83
84When the \code{connect} completes, the socket \code{s} can
85now be used to send in a request for the text of this page. The same
86socket will read the reply, and then be destroyed. That's right -
87destroyed. Client sockets are normally only used for one exchange (or
88a small set of sequential exchanges).
89
90What happens in the web server is a bit more complex. First, the web
91server creates a "server socket".
92
93\begin{verbatim}
94 #create an INET, STREAMing socket
95 serversocket = socket.socket(
96 socket.AF_INET, socket.SOCK_STREAM)
97 #bind the socket to a public host,
98 # and a well-known port
99 serversocket.bind((socket.gethostname(), 80))
100 #become a server socket
101 serversocket.listen(5)
102\end{verbatim}
103
104A couple things to notice: we used \code{socket.gethostname()}
105so that the socket would be visible to the outside world. If we had
106used \code{s.bind(('', 80))} or \code{s.bind(('localhost',
10780))} or \code{s.bind(('127.0.0.1', 80))} we would still
108have a "server" socket, but one that was only visible within the same
109machine.
110
111A second thing to note: low number ports are usually reserved for
112"well known" services (HTTP, SNMP etc). If you're playing around, use
113a nice high number (4 digits).
114
115Finally, the argument to \code{listen} tells the socket library that
116we want it to queue up as many as 5 connect requests (the normal max)
117before refusing outside connections. If the rest of the code is
118written properly, that should be plenty.
119
120OK, now we have a "server" socket, listening on port 80. Now we enter
121the mainloop of the web server:
122
123\begin{verbatim}
124 while 1:
125 #accept connections from outside
126 (clientsocket, address) = serversocket.accept()
127 #now do something with the clientsocket
128 #in this case, we'll pretend this is a threaded server
129 ct = client_thread(clientsocket)
130 ct.run()
131\end{verbatim}
132
133There's actually 3 general ways in which this loop could work -
134dispatching a thread to handle \code{clientsocket}, create a new
135process to handle \code{clientsocket}, or restructure this app
136to use non-blocking sockets, and mulitplex between our "server" socket
137and any active \code{clientsocket}s using
138\code{select}. More about that later. The important thing to
139understand now is this: this is \emph{all} a "server" socket
140does. It doesn't send any data. It doesn't receive any data. It just
141produces "client" sockets. Each \code{clientsocket} is created
142in response to some \emph{other} "client" socket doing a
143\code{connect()} to the host and port we're bound to. As soon as
144we've created that \code{clientsocket}, we go back to listening
145for more connections. The two "clients" are free to chat it up - they
146are using some dynamically allocated port which will be recycled when
147the conversation ends.
148
149\subsection{IPC} If you need fast IPC between two processes
150on one machine, you should look into whatever form of shared memory
151the platform offers. A simple protocol based around shared memory and
152locks or semaphores is by far the fastest technique.
153
154If you do decide to use sockets, bind the "server" socket to
155\code{'localhost'}. On most platforms, this will take a shortcut
156around a couple of layers of network code and be quite a bit faster.
157
158
159\section{Using a Socket}
160
161The first thing to note, is that the web browser's "client" socket and
162the web server's "client" socket are identical beasts. That is, this
163is a "peer to peer" conversation. Or to put it another way, \emph{as the
164designer, you will have to decide what the rules of etiquette are for
165a conversation}. Normally, the \code{connect}ing socket
166starts the conversation, by sending in a request, or perhaps a
167signon. But that's a design decision - it's not a rule of sockets.
168
169Now there are two sets of verbs to use for communication. You can use
170\code{send} and \code{recv}, or you can transform your
171client socket into a file-like beast and use \code{read} and
172\code{write}. The latter is the way Java presents their
173sockets. I'm not going to talk about it here, except to warn you that
174you need to use \code{flush} on sockets. These are buffered
175"files", and a common mistake is to \code{write} something, and
176then \code{read} for a reply. Without a \code{flush} in
177there, you may wait forever for the reply, because the request may
178still be in your output buffer.
179
180Now we come the major stumbling block of sockets - \code{send}
181and \code{recv} operate on the network buffers. They do not
182necessarily handle all the bytes you hand them (or expect from them),
183because their major focus is handling the network buffers. In general,
184they return when the associated network buffers have been filled
185(\code{send}) or emptied (\code{recv}). They then tell you
186how many bytes they handled. It is \emph{your} responsibility to call
187them again until your message has been completely dealt with.
188
189When a \code{recv} returns 0 bytes, it means the other side has
190closed (or is in the process of closing) the connection. You will not
191receive any more data on this connection. Ever. You may be able to
192send data successfully; I'll talk about that some on the next page.
193
194A protocol like HTTP uses a socket for only one transfer. The client
195sends a request, the reads a reply. That's it. The socket is
196discarded. This means that a client can detect the end of the reply by
197receiving 0 bytes.
198
199But if you plan to reuse your socket for further transfers, you need
200to realize that \emph{there is no "EOT" (End of Transfer) on a
201socket.} I repeat: if a socket \code{send} or
202\code{recv} returns after handling 0 bytes, the connection has
203been broken. If the connection has \emph{not} been broken, you may
204wait on a \code{recv} forever, because the socket will
205\emph{not} tell you that there's nothing more to read (for now). Now
206if you think about that a bit, you'll come to realize a fundamental
207truth of sockets: \emph{messages must either be fixed length} (yuck),
208\emph{or be delimited} (shrug), \emph{or indicate how long they are}
209(much better), \emph{or end by shutting down the connection}. The
210choice is entirely yours, (but some ways are righter than others).
211
212Assuming you don't want to end the connection, the simplest solution
213is a fixed length message:
214
215\begin{verbatim}
216 class mysocket:
217 '''demonstration class only
218 - coded for clarity, not efficiency'''
219 def __init__(self, sock=None):
220 if sock is None:
221 self.sock = socket.socket(
222 socket.AF_INET, socket.SOCK_STREAM)
223 else:
224 self.sock = sock
Andrew M. Kuchling58aa6f72006-08-09 14:05:35 +0000225
226 def connect(self, host, port):
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000227 self.sock.connect((host, port))
Andrew M. Kuchling58aa6f72006-08-09 14:05:35 +0000228
229 def mysend(self, msg):
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000230 totalsent = 0
231 while totalsent < MSGLEN:
232 sent = self.sock.send(msg[totalsent:])
233 if sent == 0:
234 raise RuntimeError, \\
235 "socket connection broken"
236 totalsent = totalsent + sent
Andrew M. Kuchling58aa6f72006-08-09 14:05:35 +0000237
238 def myreceive(self):
Andrew M. Kuchlinge8f44d62005-08-30 01:25:05 +0000239 msg = ''
240 while len(msg) < MSGLEN:
241 chunk = self.sock.recv(MSGLEN-len(msg))
242 if chunk == '':
243 raise RuntimeError, \\
244 "socket connection broken"
245 msg = msg + chunk
246 return msg
247\end{verbatim}
248
249The sending code here is usable for almost any messaging scheme - in
250Python you send strings, and you can use \code{len()} to
251determine its length (even if it has embedded \code{\e 0}
252characters). It's mostly the receiving code that gets more
253complex. (And in C, it's not much worse, except you can't use
254\code{strlen} if the message has embedded \code{\e 0}s.)
255
256The easiest enhancement is to make the first character of the message
257an indicator of message type, and have the type determine the
258length. Now you have two \code{recv}s - the first to get (at
259least) that first character so you can look up the length, and the
260second in a loop to get the rest. If you decide to go the delimited
261route, you'll be receiving in some arbitrary chunk size, (4096 or 8192
262is frequently a good match for network buffer sizes), and scanning
263what you've received for a delimiter.
264
265One complication to be aware of: if your conversational protocol
266allows multiple messages to be sent back to back (without some kind of
267reply), and you pass \code{recv} an arbitrary chunk size, you
268may end up reading the start of a following message. You'll need to
269put that aside and hold onto it, until it's needed.
270
271Prefixing the message with it's length (say, as 5 numeric characters)
272gets more complex, because (believe it or not), you may not get all 5
273characters in one \code{recv}. In playing around, you'll get
274away with it; but in high network loads, your code will very quickly
275break unless you use two \code{recv} loops - the first to
276determine the length, the second to get the data part of the
277message. Nasty. This is also when you'll discover that
278\code{send} does not always manage to get rid of everything in
279one pass. And despite having read this, you will eventually get bit by
280it!
281
282In the interests of space, building your character, (and preserving my
283competitive position), these enhancements are left as an exercise for
284the reader. Lets move on to cleaning up.
285
286\subsection{Binary Data}
287
288It is perfectly possible to send binary data over a socket. The major
289problem is that not all machines use the same formats for binary
290data. For example, a Motorola chip will represent a 16 bit integer
291with the value 1 as the two hex bytes 00 01. Intel and DEC, however,
292are byte-reversed - that same 1 is 01 00. Socket libraries have calls
293for converting 16 and 32 bit integers - \code{ntohl, htonl, ntohs,
294htons} where "n" means \emph{network} and "h" means \emph{host},
295"s" means \emph{short} and "l" means \emph{long}. Where network order
296is host order, these do nothing, but where the machine is
297byte-reversed, these swap the bytes around appropriately.
298
299In these days of 32 bit machines, the ascii representation of binary
300data is frequently smaller than the binary representation. That's
301because a surprising amount of the time, all those longs have the
302value 0, or maybe 1. The string "0" would be two bytes, while binary
303is four. Of course, this doesn't fit well with fixed-length
304messages. Decisions, decisions.
305
306\section{Disconnecting}
307
308Strictly speaking, you're supposed to use \code{shutdown} on a
309socket before you \code{close} it. The \code{shutdown} is
310an advisory to the socket at the other end. Depending on the argument
311you pass it, it can mean "I'm not going to send anymore, but I'll
312still listen", or "I'm not listening, good riddance!". Most socket
313libraries, however, are so used to programmers neglecting to use this
314piece of etiquette that normally a \code{close} is the same as
315\code{shutdown(); close()}. So in most situations, an explicit
316\code{shutdown} is not needed.
317
318One way to use \code{shutdown} effectively is in an HTTP-like
319exchange. The client sends a request and then does a
320\code{shutdown(1)}. This tells the server "This client is done
321sending, but can still receive." The server can detect "EOF" by a
322receive of 0 bytes. It can assume it has the complete request. The
323server sends a reply. If the \code{send} completes successfully
324then, indeed, the client was still receiving.
325
326Python 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.
327
328
329\subsection{When Sockets Die}
330
331Probably the worst thing about using blocking sockets is what happens
332when the other side comes down hard (without doing a
333\code{close}). Your socket is likely to hang. SOCKSTREAM is a
334reliable protocol, and it will wait a long, long time before giving up
335on a connection. If you're using threads, the entire thread is
336essentially dead. There's not much you can do about it. As long as you
337aren't doing something dumb, like holding a lock while doing a
338blocking read, the thread isn't really consuming much in the way of
339resources. Do \emph{not} try to kill the thread - part of the reason
340that threads are more efficient than processes is that they avoid the
341overhead associated with the automatic recycling of resources. In
342other words, if you do manage to kill the thread, your whole process
343is likely to be screwed up.
344
345\section{Non-blocking Sockets}
346
347If you've understood the preceeding, you already know most of what you
348need to know about the mechanics of using sockets. You'll still use
349the same calls, in much the same ways. It's just that, if you do it
350right, your app will be almost inside-out.
351
352In Python, you use \code{socket.setblocking(0)} to make it
353non-blocking. In C, it's more complex, (for one thing, you'll need to
354choose between the BSD flavor \code{O_NONBLOCK} and the almost
355indistinguishable Posix flavor \code{O_NDELAY}, which is
356completely different from \code{TCP_NODELAY}), but it's the
357exact same idea. You do this after creating the socket, but before
358using it. (Actually, if you're nuts, you can switch back and forth.)
359
360The major mechanical difference is that \code{send},
361\code{recv}, \code{connect} and \code{accept} can
362return without having done anything. You have (of course) a number of
363choices. You can check return code and error codes and generally drive
364yourself crazy. If you don't believe me, try it sometime. Your app
365will grow large, buggy and suck CPU. So let's skip the brain-dead
366solutions and do it right.
367
368Use \code{select}.
369
370In C, coding \code{select} is fairly complex. In Python, it's a
371piece of cake, but it's close enough to the C version that if you
372understand \code{select} in Python, you'll have little trouble
373with it in C.
374
375\begin{verbatim} ready_to_read, ready_to_write, in_error = \\
376 select.select(
377 potential_readers,
378 potential_writers,
379 potential_errs,
380 timeout)
381\end{verbatim}
382
383You pass \code{select} three lists: the first contains all
384sockets that you might want to try reading; the second all the sockets
385you might want to try writing to, and the last (normally left empty)
386those that you want to check for errors. You should note that a
387socket can go into more than one list. The \code{select} call is
388blocking, but you can give it a timeout. This is generally a sensible
389thing to do - give it a nice long timeout (say a minute) unless you
390have good reason to do otherwise.
391
392In return, you will get three lists. They have the sockets that are
393actually readable, writable and in error. Each of these lists is a
394subset (possbily empty) of the corresponding list you passed in. And
395if you put a socket in more than one input list, it will only be (at
396most) in one output list.
397
398If a socket is in the output readable list, you can be
399as-close-to-certain-as-we-ever-get-in-this-business that a
400\code{recv} on that socket will return \emph{something}. Same
401idea for the writable list. You'll be able to send
402\emph{something}. Maybe not all you want to, but \emph{something} is
403better than nothing. (Actually, any reasonably healthy socket will
404return as writable - it just means outbound network buffer space is
405available.)
406
407If you have a "server" socket, put it in the potential_readers
408list. If it comes out in the readable list, your \code{accept}
409will (almost certainly) work. If you have created a new socket to
410\code{connect} to someone else, put it in the ptoential_writers
411list. If it shows up in the writable list, you have a decent chance
412that it has connected.
413
414One very nasty problem with \code{select}: if somewhere in those
415input lists of sockets is one which has died a nasty death, the
416\code{select} will fail. You then need to loop through every
417single damn socket in all those lists and do a
418\code{select([sock],[],[],0)} until you find the bad one. That
419timeout of 0 means it won't take long, but it's ugly.
420
421Actually, \code{select} can be handy even with blocking sockets.
422It's one way of determining whether you will block - the socket
423returns as readable when there's something in the buffers. However,
424this still doesn't help with the problem of determining whether the
425other end is done, or just busy with something else.
426
427\textbf{Portability alert}: On Unix, \code{select} works both with
428the sockets and files. Don't try this on Windows. On Windows,
429\code{select} works with sockets only. Also note that in C, many
430of the more advanced socket options are done differently on
431Windows. In fact, on Windows I usually use threads (which work very,
432very well) with my sockets. Face it, if you want any kind of
433performance, your code will look very different on Windows than on
434Unix. (I haven't the foggiest how you do this stuff on a Mac.)
435
436\subsection{Performance}
437
438There's no question that the fastest sockets code uses non-blocking
439sockets and select to multiplex them. You can put together something
440that will saturate a LAN connection without putting any strain on the
441CPU. The trouble is that an app written this way can't do much of
442anything else - it needs to be ready to shuffle bytes around at all
443times.
444
445Assuming that your app is actually supposed to do something more than
446that, threading is the optimal solution, (and using non-blocking
447sockets will be faster than using blocking sockets). Unfortunately,
448threading support in Unixes varies both in API and quality. So the
449normal Unix solution is to fork a subprocess to deal with each
450connection. The overhead for this is significant (and don't do this on
451Windows - the overhead of process creation is enormous there). It also
452means that unless each subprocess is completely independent, you'll
453need to use another form of IPC, say a pipe, or shared memory and
454semaphores, to communicate between the parent and child processes.
455
456Finally, remember that even though blocking sockets are somewhat
457slower than non-blocking, in many cases they are the "right"
458solution. After all, if your app is driven by the data it receives
459over a socket, there's not much sense in complicating the logic just
460so your app can wait on \code{select} instead of
461\code{recv}.
462
463\end{document}