blob: 7a9b0edc1944862d71035ee0c2eb2fba31b0a6e0 [file] [log] [blame]
Senthil Kumaran6e13f132012-02-09 17:54:17 +08001.. _socket-howto:
2
Georg Brandl116aa622007-08-15 14:28:22 +00003****************************
Georg Brandl48310cd2009-01-03 21:18:54 +00004 Socket Programming HOWTO
Georg Brandl116aa622007-08-15 14:28:22 +00005****************************
6
7:Author: Gordon McMillan
8
9
10.. topic:: Abstract
11
12 Sockets are used nearly everywhere, but are one of the most severely
13 misunderstood technologies around. This is a 10,000 foot overview of sockets.
14 It's not really a tutorial - you'll still have work to do in getting things
15 operational. It doesn't cover the fine points (and there are a lot of them), but
16 I hope it will give you enough background to begin using them decently.
17
18
19Sockets
20=======
21
Martin v. Löwis987475c2011-05-29 16:54:08 +020022I'm only going to talk about INET (i.e. IPv4) sockets, but they account for at least 99% of
23the sockets in use. And I'll only talk about STREAM (i.e. TCP) sockets - unless you really
Georg Brandl116aa622007-08-15 14:28:22 +000024know what you're doing (in which case this HOWTO isn't for you!), you'll get
25better behavior and performance from a STREAM socket than anything else. I will
26try to clear up the mystery of what a socket is, as well as some hints on how to
27work with blocking and non-blocking sockets. But I'll start by talking about
28blocking sockets. You'll need to know how they work before dealing with
29non-blocking sockets.
30
31Part of the trouble with understanding these things is that "socket" can mean a
32number of subtly different things, depending on context. So first, let's make a
33distinction between a "client" socket - an endpoint of a conversation, and a
34"server" socket, which is more like a switchboard operator. The client
35application (your browser, for example) uses "client" sockets exclusively; the
36web server it's talking to uses both "server" sockets and "client" sockets.
37
38
39History
40-------
41
Ezio Melottieda19902011-05-14 09:17:52 +030042Of the various forms of :abbr:`IPC (Inter Process Communication)`,
43sockets are by far the most popular. On any given platform, there are
44likely to be other forms of IPC that are faster, but for
45cross-platform communication, sockets are about the only game in town.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47They were invented in Berkeley as part of the BSD flavor of Unix. They spread
48like wildfire with the Internet. With good reason --- the combination of sockets
49with INET makes talking to arbitrary machines around the world unbelievably easy
50(at least compared to other schemes).
51
52
53Creating a Socket
54=================
55
56Roughly speaking, when you clicked on the link that brought you to this page,
57your browser did something like the following::
58
Antoine Pitrou83454512011-12-05 01:37:34 +010059 # create an INET, STREAMing socket
Collin Winter4c6a1402007-09-10 00:47:20 +000060 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Antoine Pitrou83454512011-12-05 01:37:34 +010061 # now connect to the web server on port 80 - the normal http port
62 s.connect(("www.python.org", 80))
Georg Brandl116aa622007-08-15 14:28:22 +000063
Ezio Melottieda19902011-05-14 09:17:52 +030064When the ``connect`` completes, the socket ``s`` can be used to send
65in a request for the text of the page. The same socket will read the
66reply, and then be destroyed. That's right, destroyed. Client sockets
67are normally only used for one exchange (or a small set of sequential
68exchanges).
Georg Brandl116aa622007-08-15 14:28:22 +000069
70What happens in the web server is a bit more complex. First, the web server
Ezio Melottieda19902011-05-14 09:17:52 +030071creates a "server socket"::
Georg Brandl116aa622007-08-15 14:28:22 +000072
Antoine Pitrou83454512011-12-05 01:37:34 +010073 # create an INET, STREAMing socket
74 serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
75 # bind the socket to a public host, and a well-known port
Georg Brandl116aa622007-08-15 14:28:22 +000076 serversocket.bind((socket.gethostname(), 80))
Antoine Pitrou83454512011-12-05 01:37:34 +010077 # become a server socket
Georg Brandl116aa622007-08-15 14:28:22 +000078 serversocket.listen(5)
79
80A couple things to notice: we used ``socket.gethostname()`` so that the socket
Georg Brandla2046362013-04-14 10:59:04 +020081would be visible to the outside world. If we had used ``s.bind(('localhost',
8280))`` or ``s.bind(('127.0.0.1', 80))`` we would still have a "server" socket,
83but one that was only visible within the same machine. ``s.bind(('', 80))``
84specifies that the socket is reachable by any address the machine happens to
85have.
Georg Brandl116aa622007-08-15 14:28:22 +000086
87A second thing to note: low number ports are usually reserved for "well known"
88services (HTTP, SNMP etc). If you're playing around, use a nice high number (4
89digits).
90
91Finally, the argument to ``listen`` tells the socket library that we want it to
92queue up as many as 5 connect requests (the normal max) before refusing outside
93connections. If the rest of the code is written properly, that should be plenty.
94
Ezio Melottieda19902011-05-14 09:17:52 +030095Now that we have a "server" socket, listening on port 80, we can enter the
Georg Brandl116aa622007-08-15 14:28:22 +000096mainloop of the web server::
97
Collin Winter4c6a1402007-09-10 00:47:20 +000098 while True:
Antoine Pitrou83454512011-12-05 01:37:34 +010099 # accept connections from outside
Georg Brandl116aa622007-08-15 14:28:22 +0000100 (clientsocket, address) = serversocket.accept()
Antoine Pitrou83454512011-12-05 01:37:34 +0100101 # now do something with the clientsocket
102 # in this case, we'll pretend this is a threaded server
Georg Brandl116aa622007-08-15 14:28:22 +0000103 ct = client_thread(clientsocket)
104 ct.run()
105
106There's actually 3 general ways in which this loop could work - dispatching a
107thread to handle ``clientsocket``, create a new process to handle
108``clientsocket``, or restructure this app to use non-blocking sockets, and
109mulitplex between our "server" socket and any active ``clientsocket``\ s using
110``select``. More about that later. The important thing to understand now is
111this: this is *all* a "server" socket does. It doesn't send any data. It doesn't
112receive any data. It just produces "client" sockets. Each ``clientsocket`` is
113created in response to some *other* "client" socket doing a ``connect()`` to the
114host and port we're bound to. As soon as we've created that ``clientsocket``, we
115go back to listening for more connections. The two "clients" are free to chat it
116up - they are using some dynamically allocated port which will be recycled when
117the conversation ends.
118
119
120IPC
121---
122
123If you need fast IPC between two processes on one machine, you should look into
Antoine Pitrou8e644f02011-12-05 01:43:32 +0100124pipes or shared memory. If you do decide to use AF_INET sockets, bind the
125"server" socket to ``'localhost'``. On most platforms, this will take a
126shortcut around a couple of layers of network code and be quite a bit faster.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
Antoine Pitrou8e644f02011-12-05 01:43:32 +0100128.. seealso::
129 The :mod:`multiprocessing` integrates cross-platform IPC into a higher-level
130 API.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132
133Using a Socket
134==============
135
136The first thing to note, is that the web browser's "client" socket and the web
137server's "client" socket are identical beasts. That is, this is a "peer to peer"
138conversation. Or to put it another way, *as the designer, you will have to
139decide what the rules of etiquette are for a conversation*. Normally, the
140``connect``\ ing socket starts the conversation, by sending in a request, or
141perhaps a signon. But that's a design decision - it's not a rule of sockets.
142
143Now there are two sets of verbs to use for communication. You can use ``send``
144and ``recv``, or you can transform your client socket into a file-like beast and
Ezio Melottieda19902011-05-14 09:17:52 +0300145use ``read`` and ``write``. The latter is the way Java presents its sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000146I'm not going to talk about it here, except to warn you that you need to use
147``flush`` on sockets. These are buffered "files", and a common mistake is to
148``write`` something, and then ``read`` for a reply. Without a ``flush`` in
149there, you may wait forever for the reply, because the request may still be in
150your output buffer.
151
Sandro Tosicfdba612012-04-23 19:45:07 +0200152Now we come to the major stumbling block of sockets - ``send`` and ``recv`` operate
Georg Brandl116aa622007-08-15 14:28:22 +0000153on the network buffers. They do not necessarily handle all the bytes you hand
154them (or expect from them), because their major focus is handling the network
155buffers. In general, they return when the associated network buffers have been
156filled (``send``) or emptied (``recv``). They then tell you how many bytes they
157handled. It is *your* responsibility to call them again until your message has
158been completely dealt with.
159
160When a ``recv`` returns 0 bytes, it means the other side has closed (or is in
161the process of closing) the connection. You will not receive any more data on
162this connection. Ever. You may be able to send data successfully; I'll talk
Sandro Tosicfdba612012-04-23 19:45:07 +0200163more about this later.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165A protocol like HTTP uses a socket for only one transfer. The client sends a
Ezio Melottieda19902011-05-14 09:17:52 +0300166request, then reads a reply. That's it. The socket is discarded. This means that
Georg Brandl116aa622007-08-15 14:28:22 +0000167a client can detect the end of the reply by receiving 0 bytes.
168
169But if you plan to reuse your socket for further transfers, you need to realize
Ezio Melottieda19902011-05-14 09:17:52 +0300170that *there is no* :abbr:`EOT (End of Transfer)` *on a socket.* I repeat: if a socket
Georg Brandl116aa622007-08-15 14:28:22 +0000171``send`` or ``recv`` returns after handling 0 bytes, the connection has been
172broken. If the connection has *not* been broken, you may wait on a ``recv``
173forever, because the socket will *not* tell you that there's nothing more to
174read (for now). Now if you think about that a bit, you'll come to realize a
175fundamental truth of sockets: *messages must either be fixed length* (yuck), *or
176be delimited* (shrug), *or indicate how long they are* (much better), *or end by
177shutting down the connection*. The choice is entirely yours, (but some ways are
178righter than others).
179
180Assuming you don't want to end the connection, the simplest solution is a fixed
181length message::
182
183 class mysocket:
Georg Brandl48310cd2009-01-03 21:18:54 +0000184 """demonstration class only
Georg Brandl116aa622007-08-15 14:28:22 +0000185 - coded for clarity, not efficiency
Collin Winter4c6a1402007-09-10 00:47:20 +0000186 """
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188 def __init__(self, sock=None):
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000189 if sock is None:
190 self.sock = socket.socket(
191 socket.AF_INET, socket.SOCK_STREAM)
192 else:
193 self.sock = sock
Georg Brandl116aa622007-08-15 14:28:22 +0000194
195 def connect(self, host, port):
Collin Winter4c6a1402007-09-10 00:47:20 +0000196 self.sock.connect((host, port))
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198 def mysend(self, msg):
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000199 totalsent = 0
200 while totalsent < MSGLEN:
201 sent = self.sock.send(msg[totalsent:])
202 if sent == 0:
203 raise RuntimeError("socket connection broken")
204 totalsent = totalsent + sent
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206 def myreceive(self):
Martin v. Löwisa7eaa412011-05-29 17:15:44 +0200207 msg = b''
Collin Winter4c6a1402007-09-10 00:47:20 +0000208 while len(msg) < MSGLEN:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000209 chunk = self.sock.recv(MSGLEN-len(msg))
Martin v. Löwisa7eaa412011-05-29 17:15:44 +0200210 if chunk == b'':
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000211 raise RuntimeError("socket connection broken")
212 msg = msg + chunk
Collin Winter4c6a1402007-09-10 00:47:20 +0000213 return msg
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215The sending code here is usable for almost any messaging scheme - in Python you
216send strings, and you can use ``len()`` to determine its length (even if it has
217embedded ``\0`` characters). It's mostly the receiving code that gets more
218complex. (And in C, it's not much worse, except you can't use ``strlen`` if the
219message has embedded ``\0``\ s.)
220
221The easiest enhancement is to make the first character of the message an
222indicator of message type, and have the type determine the length. Now you have
223two ``recv``\ s - the first to get (at least) that first character so you can
224look up the length, and the second in a loop to get the rest. If you decide to
225go the delimited route, you'll be receiving in some arbitrary chunk size, (4096
226or 8192 is frequently a good match for network buffer sizes), and scanning what
227you've received for a delimiter.
228
229One complication to be aware of: if your conversational protocol allows multiple
230messages to be sent back to back (without some kind of reply), and you pass
231``recv`` an arbitrary chunk size, you may end up reading the start of a
232following message. You'll need to put that aside and hold onto it, until it's
233needed.
234
235Prefixing the message with it's length (say, as 5 numeric characters) gets more
236complex, because (believe it or not), you may not get all 5 characters in one
237``recv``. In playing around, you'll get away with it; but in high network loads,
238your code will very quickly break unless you use two ``recv`` loops - the first
239to determine the length, the second to get the data part of the message. Nasty.
240This is also when you'll discover that ``send`` does not always manage to get
241rid of everything in one pass. And despite having read this, you will eventually
242get bit by it!
243
244In the interests of space, building your character, (and preserving my
245competitive position), these enhancements are left as an exercise for the
246reader. Lets move on to cleaning up.
247
248
249Binary Data
250-----------
251
252It is perfectly possible to send binary data over a socket. The major problem is
253that not all machines use the same formats for binary data. For example, a
254Motorola chip will represent a 16 bit integer with the value 1 as the two hex
255bytes 00 01. Intel and DEC, however, are byte-reversed - that same 1 is 01 00.
256Socket libraries have calls for converting 16 and 32 bit integers - ``ntohl,
257htonl, ntohs, htons`` where "n" means *network* and "h" means *host*, "s" means
258*short* and "l" means *long*. Where network order is host order, these do
259nothing, but where the machine is byte-reversed, these swap the bytes around
260appropriately.
261
262In these days of 32 bit machines, the ascii representation of binary data is
263frequently smaller than the binary representation. That's because a surprising
264amount of the time, all those longs have the value 0, or maybe 1. The string "0"
265would be two bytes, while binary is four. Of course, this doesn't fit well with
266fixed-length messages. Decisions, decisions.
267
268
269Disconnecting
270=============
271
272Strictly speaking, you're supposed to use ``shutdown`` on a socket before you
273``close`` it. The ``shutdown`` is an advisory to the socket at the other end.
274Depending on the argument you pass it, it can mean "I'm not going to send
275anymore, but I'll still listen", or "I'm not listening, good riddance!". Most
276socket libraries, however, are so used to programmers neglecting to use this
277piece of etiquette that normally a ``close`` is the same as ``shutdown();
278close()``. So in most situations, an explicit ``shutdown`` is not needed.
279
280One way to use ``shutdown`` effectively is in an HTTP-like exchange. The client
281sends a request and then does a ``shutdown(1)``. This tells the server "This
282client is done sending, but can still receive." The server can detect "EOF" by
283a receive of 0 bytes. It can assume it has the complete request. The server
284sends a reply. If the ``send`` completes successfully then, indeed, the client
285was still receiving.
286
287Python takes the automatic shutdown a step further, and says that when a socket
288is garbage collected, it will automatically do a ``close`` if it's needed. But
289relying on this is a very bad habit. If your socket just disappears without
290doing a ``close``, the socket at the other end may hang indefinitely, thinking
291you're just being slow. *Please* ``close`` your sockets when you're done.
292
293
294When Sockets Die
295----------------
296
297Probably the worst thing about using blocking sockets is what happens when the
298other side comes down hard (without doing a ``close``). Your socket is likely to
Antoine Pitrou5b73ca42011-12-05 01:46:35 +0100299hang. TCP is a reliable protocol, and it will wait a long, long time
Georg Brandl116aa622007-08-15 14:28:22 +0000300before giving up on a connection. If you're using threads, the entire thread is
301essentially dead. There's not much you can do about it. As long as you aren't
302doing something dumb, like holding a lock while doing a blocking read, the
303thread isn't really consuming much in the way of resources. Do *not* try to kill
304the thread - part of the reason that threads are more efficient than processes
305is that they avoid the overhead associated with the automatic recycling of
306resources. In other words, if you do manage to kill the thread, your whole
307process is likely to be screwed up.
308
309
310Non-blocking Sockets
311====================
312
Georg Brandl4b054662010-10-06 08:56:53 +0000313If you've understood the preceding, you already know most of what you need to
Georg Brandl116aa622007-08-15 14:28:22 +0000314know about the mechanics of using sockets. You'll still use the same calls, in
315much the same ways. It's just that, if you do it right, your app will be almost
316inside-out.
317
318In Python, you use ``socket.setblocking(0)`` to make it non-blocking. In C, it's
319more complex, (for one thing, you'll need to choose between the BSD flavor
320``O_NONBLOCK`` and the almost indistinguishable Posix flavor ``O_NDELAY``, which
321is completely different from ``TCP_NODELAY``), but it's the exact same idea. You
322do this after creating the socket, but before using it. (Actually, if you're
323nuts, you can switch back and forth.)
324
325The major mechanical difference is that ``send``, ``recv``, ``connect`` and
326``accept`` can return without having done anything. You have (of course) a
327number of choices. You can check return code and error codes and generally drive
328yourself crazy. If you don't believe me, try it sometime. Your app will grow
329large, buggy and suck CPU. So let's skip the brain-dead solutions and do it
330right.
331
332Use ``select``.
333
334In C, coding ``select`` is fairly complex. In Python, it's a piece of cake, but
335it's close enough to the C version that if you understand ``select`` in Python,
Ezio Melottieda19902011-05-14 09:17:52 +0300336you'll have little trouble with it in C::
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338 ready_to_read, ready_to_write, in_error = \
339 select.select(
Georg Brandl48310cd2009-01-03 21:18:54 +0000340 potential_readers,
341 potential_writers,
342 potential_errs,
Georg Brandl116aa622007-08-15 14:28:22 +0000343 timeout)
344
345You pass ``select`` three lists: the first contains all sockets that you might
346want to try reading; the second all the sockets you might want to try writing
347to, and the last (normally left empty) those that you want to check for errors.
348You should note that a socket can go into more than one list. The ``select``
349call is blocking, but you can give it a timeout. This is generally a sensible
350thing to do - give it a nice long timeout (say a minute) unless you have good
351reason to do otherwise.
352
Ezio Melottieda19902011-05-14 09:17:52 +0300353In return, you will get three lists. They contain the sockets that are actually
Christian Heimesc3f30c42008-02-22 16:37:40 +0000354readable, writable and in error. Each of these lists is a subset (possibly
Eli Bendersky46ab96a2011-05-22 06:56:15 +0300355empty) of the corresponding list you passed in.
Georg Brandl116aa622007-08-15 14:28:22 +0000356
357If a socket is in the output readable list, you can be
358as-close-to-certain-as-we-ever-get-in-this-business that a ``recv`` on that
359socket will return *something*. Same idea for the writable list. You'll be able
360to send *something*. Maybe not all you want to, but *something* is better than
361nothing. (Actually, any reasonably healthy socket will return as writable - it
362just means outbound network buffer space is available.)
363
364If you have a "server" socket, put it in the potential_readers list. If it comes
365out in the readable list, your ``accept`` will (almost certainly) work. If you
366have created a new socket to ``connect`` to someone else, put it in the
Christian Heimesc3f30c42008-02-22 16:37:40 +0000367potential_writers list. If it shows up in the writable list, you have a decent
Georg Brandl116aa622007-08-15 14:28:22 +0000368chance that it has connected.
369
Georg Brandl116aa622007-08-15 14:28:22 +0000370Actually, ``select`` can be handy even with blocking sockets. It's one way of
371determining whether you will block - the socket returns as readable when there's
372something in the buffers. However, this still doesn't help with the problem of
373determining whether the other end is done, or just busy with something else.
374
375**Portability alert**: On Unix, ``select`` works both with the sockets and
376files. Don't try this on Windows. On Windows, ``select`` works with sockets
377only. Also note that in C, many of the more advanced socket options are done
378differently on Windows. In fact, on Windows I usually use threads (which work
Martin v. Löwis2d449aa2011-06-06 10:25:55 +0200379very, very well) with my sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000380
381