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