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