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