/Doc/howto/sockets.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 420 lines · 338 code · 82 blank · 0 comment · 0 complexity · cd40b2921ca9c0f018d135b461d97312 MD5 · raw file

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