PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/Socket Programming HOWTO.html

https://bitbucket.org/DavidVilla/python-socket-programming-howto-spanish-translation
HTML | 650 lines | 559 code | 87 blank | 4 comment | 0 complexity | 095c2aa430cab33e40840356a26e8a79 MD5 | raw file
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2. <html><head>
  3. <link rel="STYLESHEET" href="Socket%20Programming%20HOWTO_files/sockets.css" type="text/css">
  4. <link rel="first" href="http://www.amk.ca/python/howto/sockets/sockets.html" title="Socket Programming HOWTO">
  5. <link rel="contents" href="http://www.amk.ca/python/howto/sockets/contents.html" title="Contents"><link rel="last" href="http://www.amk.ca/python/howto/sockets/about.html" title="About this document...">
  6. <link rel="help" href="http://www.amk.ca/python/howto/sockets/about.html" title="About this document...">
  7. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  8. <meta name="aesop" content="information">
  9. <meta name="description" content="Socket Programming HOWTO">
  10. <meta name="keywords" content="sockets">
  11. <meta name="resource-type" content="document">
  12. <meta name="distribution" content="global">
  13. <title>Socket Programming HOWTO</title></head>
  14. <body>
  15. <div class="navigation">
  16. <table align="center" cellpadding="0" cellspacing="2" width="100%">
  17. <tbody><tr>
  18. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  19. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  20. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  21. <td align="center" width="100%">Socket Programming HOWTO</td>
  22. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  23. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  24. </tr></tbody></table>
  25. <br><hr>
  26. </div>
  27. <!--End of Navigation Panel-->
  28. <div class="titlepage">
  29. <center>
  30. <h1>Socket Programming HOWTO</h1>
  31. <p><b><font size="+2">Gordon McMillan</font></b></p>
  32. <p><span class="email">gmcm@hypernet.com</span></p>
  33. <p>
  34. </p></center>
  35. </div>
  36. <p>
  37. </p><h3>Abstract:</h3>
  38. <div class="ABSTRACT">
  39. Sockets are used nearly everywhere, but are one of the most severely
  40. misunderstood technologies around. This is a 10,000 foot overview of
  41. sockets. It's not really a tutorial - you'll still have work to do in
  42. getting things operational. It doesn't cover the fine points (and there
  43. are a lot of them), but I hope it will give you enough background to
  44. begin using them decently.
  45. <p>
  46. This document is available from the Python HOWTO page at
  47. <a class="url" href="http://www.python.org/doc/howto">http://www.python.org/doc/howto</a>.
  48. </p><p>
  49. </p></div>
  50. <p>
  51. </p><p>
  52. <br>
  53. <br></p><h2><a name="SECTION000100000000000000000">
  54. Contents</a>
  55. </h2>
  56. <!--Table of Contents-->
  57. <ul class="TofC">
  58. <li><a href="http://www.amk.ca/python/howto/sockets/sockets.html">1 Sockets</a>
  59. <ul>
  60. <li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000210000000000000000">1.1 History</a>
  61. </li></ul>
  62. </li><li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000300000000000000000">2 Creating a Socket</a>
  63. <ul>
  64. <li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000310000000000000000">2.1 IPC</a>
  65. </li></ul>
  66. </li><li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000400000000000000000">3 Using a Socket</a>
  67. <ul>
  68. <li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000410000000000000000">3.1 Binary Data</a>
  69. </li></ul>
  70. </li><li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000500000000000000000">4 Disconnecting</a>
  71. <ul>
  72. <li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000510000000000000000">4.1 When Sockets Die</a>
  73. </li></ul>
  74. </li><li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000600000000000000000">5 Non-blocking Sockets</a>
  75. <ul>
  76. <li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000610000000000000000">5.1 Performance</a>
  77. </li></ul>
  78. </li><li><a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000700000000000000000">About this document ...</a>
  79. </li></ul>
  80. <!--End of Table of Contents-->
  81. <p>
  82. </p><h1><a name="SECTION000200000000000000000">
  83. 1 Sockets</a>
  84. </h1>
  85. <p>
  86. Sockets are used nearly everywhere, but are one of the most severely
  87. misunderstood technologies around. This is a 10,000 foot overview of
  88. sockets. It's not really a tutorial - you'll still have work to do in
  89. getting things working. It doesn't cover the fine points (and there
  90. are a lot of them), but I hope it will give you enough background to
  91. begin using them decently.
  92. </p><p>
  93. I'm only going to talk about INET sockets, but they account for at
  94. least 99% of the sockets in use. And I'll only talk about STREAM
  95. sockets - unless you really know what you're doing (in which case this
  96. HOWTO isn't for you!), you'll get better behavior and performance from
  97. a STREAM socket than anything else. I will try to clear up the mystery
  98. of what a socket is, as well as some hints on how to work with
  99. blocking and non-blocking sockets. But I'll start by talking about
  100. blocking sockets. You'll need to know how they work before dealing
  101. with non-blocking sockets.
  102. </p><p>
  103. Part of the trouble with understanding these things is that "socket"
  104. can mean a number of subtly different things, depending on context. So
  105. first, let's make a distinction between a "client" socket - an
  106. endpoint of a conversation, and a "server" socket, which is more like
  107. a switchboard operator. The client application (your browser, for
  108. example) uses "client" sockets exclusively; the web server it's
  109. talking to uses both "server" sockets and "client" sockets.
  110. </p><p>
  111. </p><h2><a name="SECTION000210000000000000000">
  112. 1.1 History</a>
  113. </h2>
  114. <p>
  115. Of the various forms of IPC (<i>Inter Process Communication</i>),
  116. sockets are by far the most popular. On any given platform, there are
  117. likely to be other forms of IPC that are faster, but for
  118. cross-platform communication, sockets are about the only game in town.
  119. </p><p>
  120. They were invented in Berkeley as part of the BSD flavor of Unix. They
  121. spread like wildfire with the Internet. With good reason -- the
  122. combination of sockets with INET makes talking to arbitrary machines
  123. around the world unbelievably easy (at least compared to other
  124. schemes).
  125. </p><p>
  126. </p><h1><a name="SECTION000300000000000000000">
  127. 2 Creating a Socket</a>
  128. </h1>
  129. <p>
  130. Roughly speaking, when you clicked on the link that brought you to
  131. this page, your browser did something like the following:
  132. </p><p>
  133. </p><div class="verbatim"><pre> #create an INET, STREAMing socket
  134. s = socket.socket(
  135. socket.AF_INET, socket.SOCK_STREAM)
  136. #now connect to the web server on port 80
  137. # - the normal http port
  138. s.connect(("www.mcmillan-inc.com", 80))
  139. </pre></div>
  140. <p>
  141. When the <code>connect</code> completes, the socket <code>s</code> can
  142. now be used to send in a request for the text of this page. The same
  143. socket will read the reply, and then be destroyed. That's right -
  144. destroyed. Client sockets are normally only used for one exchange (or
  145. a small set of sequential exchanges).
  146. </p><p>
  147. What happens in the web server is a bit more complex. First, the web
  148. server creates a "server socket".
  149. </p><p>
  150. </p><div class="verbatim"><pre> #create an INET, STREAMing socket
  151. serversocket = socket.socket(
  152. socket.AF_INET, socket.SOCK_STREAM)
  153. #bind the socket to a public host,
  154. # and a well-known port
  155. serversocket.bind((socket.gethostname(), 80))
  156. #become a server socket
  157. serversocket.listen(5)
  158. </pre></div>
  159. <p>
  160. A couple things to notice: we used <code>socket.gethostname()</code>
  161. so that the socket would be visible to the outside world. If we had
  162. used <code>s.bind(('', 80))</code> or <code>s.bind(('localhost',
  163. 80))</code> or <code>s.bind(('127.0.0.1', 80))</code> we would still
  164. have a "server" socket, but one that was only visible within the same
  165. machine.
  166. </p><p>
  167. A second thing to note: low number ports are usually reserved for
  168. "well known" services (HTTP, SNMP etc). If you're playing around, use
  169. a nice high number (4 digits).
  170. </p><p>
  171. Finally, the argument to <code>listen</code> tells the socket library that
  172. we want it to queue up as many as 5 connect requests (the normal max)
  173. before refusing outside connections. If the rest of the code is
  174. written properly, that should be plenty.
  175. </p><p>
  176. OK, now we have a "server" socket, listening on port 80. Now we enter
  177. the mainloop of the web server:
  178. </p><p>
  179. </p><div class="verbatim"><pre> while 1:
  180. #accept connections from outside
  181. (clientsocket, address) = serversocket.accept()
  182. #now do something with the clientsocket
  183. #in this case, we'll pretend this is a threaded server
  184. ct = client_thread(clientsocket)
  185. ct.run()
  186. </pre></div>
  187. <p>
  188. There's actually 3 general ways in which this loop could work -
  189. dispatching a thread to handle <code>clientsocket</code>, create a new
  190. process to handle <code>clientsocket</code>, or restructure this app
  191. to use non-blocking sockets, and mulitplex between our "server" socket
  192. and any active <code>clientsocket</code>s using
  193. <code>select</code>. More about that later. The important thing to
  194. understand now is this: this is <i>all</i> a "server" socket
  195. does. It doesn't send any data. It doesn't receive any data. It just
  196. produces "client" sockets. Each <code>clientsocket</code> is created
  197. in response to some <i>other</i> "client" socket doing a
  198. <code>connect()</code> to the host and port we're bound to. As soon as
  199. we've created that <code>clientsocket</code>, we go back to listening
  200. for more connections. The two "clients" are free to chat it up - they
  201. are using some dynamically allocated port which will be recycled when
  202. the conversation ends.
  203. </p><p>
  204. </p><h2><a name="SECTION000310000000000000000">
  205. 2.1 IPC</a>
  206. </h2> If you need fast IPC between two processes
  207. on one machine, you should look into whatever form of shared memory
  208. the platform offers. A simple protocol based around shared memory and
  209. locks or semaphores is by far the fastest technique.
  210. <p>
  211. If you do decide to use sockets, bind the "server" socket to
  212. <code>'localhost'</code>. On most platforms, this will take a shortcut
  213. around a couple of layers of network code and be quite a bit faster.
  214. </p><p>
  215. </p><h1><a name="SECTION000400000000000000000">
  216. 3 Using a Socket</a>
  217. </h1>
  218. <p>
  219. The first thing to note, is that the web browser's "client" socket and
  220. the web server's "client" socket are identical beasts. That is, this
  221. is a "peer to peer" conversation. Or to put it another way, <i>as the
  222. designer, you will have to decide what the rules of etiquette are for
  223. a conversation</i>. Normally, the <code>connect</code>ing socket
  224. starts the conversation, by sending in a request, or perhaps a
  225. signon. But that's a design decision - it's not a rule of sockets.
  226. </p><p>
  227. Now there are two sets of verbs to use for communication. You can use
  228. <code>send</code> and <code>recv</code>, or you can transform your
  229. client socket into a file-like beast and use <code>read</code> and
  230. <code>write</code>. The latter is the way Java presents their
  231. sockets. I'm not going to talk about it here, except to warn you that
  232. you need to use <code>flush</code> on sockets. These are buffered
  233. "files", and a common mistake is to <code>write</code> something, and
  234. then <code>read</code> for a reply. Without a <code>flush</code> in
  235. there, you may wait forever for the reply, because the request may
  236. still be in your output buffer.
  237. </p><p>
  238. Now we come the major stumbling block of sockets - <code>send</code>
  239. and <code>recv</code> operate on the network buffers. They do not
  240. necessarily handle all the bytes you hand them (or expect from them),
  241. because their major focus is handling the network buffers. In general,
  242. they return when the associated network buffers have been filled
  243. (<code>send</code>) or emptied (<code>recv</code>). They then tell you
  244. how many bytes they handled. It is <i>your</i> responsibility to call
  245. them again until your message has been completely dealt with.
  246. </p><p>
  247. When a <code>recv</code> returns 0 bytes, it means the other side has
  248. closed (or is in the process of closing) the connection. You will not
  249. receive any more data on this connection. Ever. You may be able to
  250. send data successfully; I'll talk about that some on the next page.
  251. </p><p>
  252. A protocol like HTTP uses a socket for only one transfer. The client
  253. sends a request, the reads a reply. That's it. The socket is
  254. discarded. This means that a client can detect the end of the reply by
  255. receiving 0 bytes.
  256. </p><p>
  257. But if you plan to reuse your socket for further transfers, you need
  258. to realize that <i>there is no "EOT" (End of Transfer) on a
  259. socket.</i> I repeat: if a socket <code>send</code> or
  260. <code>recv</code> returns after handling 0 bytes, the connection has
  261. been broken. If the connection has <i>not</i> been broken, you may
  262. wait on a <code>recv</code> forever, because the socket will
  263. <i>not</i> tell you that there's nothing more to read (for now). Now
  264. if you think about that a bit, you'll come to realize a fundamental
  265. truth of sockets: <i>messages must either be fixed length</i> (yuck),
  266. <i>or be delimited</i> (shrug), <i>or indicate how long they are</i>
  267. (much better), <i>or end by shutting down the connection</i>. The
  268. choice is entirely yours, (but some ways are righter than others).
  269. </p><p>
  270. Assuming you don't want to end the connection, the simplest solution
  271. is a fixed length message:
  272. </p><p>
  273. </p><div class="verbatim"><pre> class mysocket:
  274. '''demonstration class only
  275. - coded for clarity, not efficiency'''
  276. def __init__(self, sock=None):
  277. if sock is None:
  278. self.sock = socket.socket(
  279. socket.AF_INET, socket.SOCK_STREAM)
  280. else:
  281. self.sock = sock
  282. def connect(host, port):
  283. self.sock.connect((host, port))
  284. def mysend(msg):
  285. totalsent = 0
  286. while totalsent &lt; MSGLEN:
  287. sent = self.sock.send(msg[totalsent:])
  288. if sent == 0:
  289. raise RuntimeError, \\
  290. "socket connection broken"
  291. totalsent = totalsent + sent
  292. def myreceive():
  293. msg = ''
  294. while len(msg) &lt; MSGLEN:
  295. chunk = self.sock.recv(MSGLEN-len(msg))
  296. if chunk == '':
  297. raise RuntimeError, \\
  298. "socket connection broken"
  299. msg = msg + chunk
  300. return msg
  301. </pre></div>
  302. <p>
  303. The sending code here is usable for almost any messaging scheme - in
  304. Python you send strings, and you can use <code>len()</code> to
  305. determine its length (even if it has embedded <code>\0</code>
  306. characters). It's mostly the receiving code that gets more
  307. complex. (And in C, it's not much worse, except you can't use
  308. <code>strlen</code> if the message has embedded <code>\0</code>s.)
  309. </p><p>
  310. The easiest enhancement is to make the first character of the message
  311. an indicator of message type, and have the type determine the
  312. length. Now you have two <code>recv</code>s - the first to get (at
  313. least) that first character so you can look up the length, and the
  314. second in a loop to get the rest. If you decide to go the delimited
  315. route, you'll be receiving in some arbitrary chunk size, (4096 or 8192
  316. is frequently a good match for network buffer sizes), and scanning
  317. what you've received for a delimiter.
  318. </p><p>
  319. One complication to be aware of: if your conversational protocol
  320. allows multiple messages to be sent back to back (without some kind of
  321. reply), and you pass <code>recv</code> an arbitrary chunk size, you
  322. may end up reading the start of a following message. You'll need to
  323. put that aside and hold onto it, until it's needed.
  324. </p><p>
  325. Prefixing the message with it's length (say, as 5 numeric characters)
  326. gets more complex, because (believe it or not), you may not get all 5
  327. characters in one <code>recv</code>. In playing around, you'll get
  328. away with it; but in high network loads, your code will very quickly
  329. break unless you use two <code>recv</code> loops - the first to
  330. determine the length, the second to get the data part of the
  331. message. Nasty. This is also when you'll discover that
  332. <code>send</code> does not always manage to get rid of everything in
  333. one pass. And despite having read this, you will eventually get bit by
  334. it!
  335. </p><p>
  336. In the interests of space, building your character, (and preserving my
  337. competitive position), these enhancements are left as an exercise for
  338. the reader. Lets move on to cleaning up.
  339. </p><p>
  340. </p><h2><a name="SECTION000410000000000000000">
  341. 3.1 Binary Data</a>
  342. </h2>
  343. <p>
  344. It is perfectly possible to send binary data over a socket. The major
  345. problem is that not all machines use the same formats for binary
  346. data. For example, a Motorola chip will represent a 16 bit integer
  347. with the value 1 as the two hex bytes 00 01. Intel and DEC, however,
  348. are byte-reversed - that same 1 is 01 00. Socket libraries have calls
  349. for converting 16 and 32 bit integers - <code>ntohl, htonl, ntohs,
  350. htons</code> where "n" means <i>network</i> and "h" means <i>host</i>,
  351. "s" means <i>short</i> and "l" means <i>long</i>. Where network order
  352. is host order, these do nothing, but where the machine is
  353. byte-reversed, these swap the bytes around appropriately.
  354. </p><p>
  355. In these days of 32 bit machines, the ascii representation of binary
  356. data is frequently smaller than the binary representation. That's
  357. because a surprising amount of the time, all those longs have the
  358. value 0, or maybe 1. The string "0" would be two bytes, while binary
  359. is four. Of course, this doesn't fit well with fixed-length
  360. messages. Decisions, decisions.
  361. </p><p>
  362. </p><h1><a name="SECTION000500000000000000000">
  363. 4 Disconnecting</a>
  364. </h1>
  365. <p>
  366. Strictly speaking, you're supposed to use <code>shutdown</code> on a
  367. socket before you <code>close</code> it. The <code>shutdown</code> is
  368. an advisory to the socket at the other end. Depending on the argument
  369. you pass it, it can mean "I'm not going to send anymore, but I'll
  370. still listen", or "I'm not listening, good riddance!". Most socket
  371. libraries, however, are so used to programmers neglecting to use this
  372. piece of etiquette that normally a <code>close</code> is the same as
  373. <code>shutdown(); close()</code>. So in most situations, an explicit
  374. <code>shutdown</code> is not needed.
  375. </p><p>
  376. One way to use <code>shutdown</code> effectively is in an HTTP-like
  377. exchange. The client sends a request and then does a
  378. <code>shutdown(1)</code>. This tells the server "This client is done
  379. sending, but can still receive." The server can detect "EOF" by a
  380. receive of 0 bytes. It can assume it has the complete request. The
  381. server sends a reply. If the <code>send</code> completes successfully
  382. then, indeed, the client was still receiving.
  383. </p><p>
  384. Python takes the automatic shutdown a step further, and says that when
  385. a socket is garbage collected, it will automatically do a <code>close</code> if it's needed. But relying on this is a very bad habit. If your socket just disappears without doing a <code>close</code>, the socket at the other end may hang indefinitely, thinking you're just being slow. <i>Please</i> <code>close</code> your sockets when you're done.
  386. </p><p>
  387. </p><h2><a name="SECTION000510000000000000000">
  388. 4.1 When Sockets Die</a>
  389. </h2>
  390. <p>
  391. Probably the worst thing about using blocking sockets is what happens
  392. when the other side comes down hard (without doing a
  393. <code>close</code>). Your socket is likely to hang. SOCKSTREAM is a
  394. reliable protocol, and it will wait a long, long time before giving up
  395. on a connection. If you're using threads, the entire thread is
  396. essentially dead. There's not much you can do about it. As long as you
  397. aren't doing something dumb, like holding a lock while doing a
  398. blocking read, the thread isn't really consuming much in the way of
  399. resources. Do <i>not</i> try to kill the thread - part of the reason
  400. that threads are more efficient than processes is that they avoid the
  401. overhead associated with the automatic recycling of resources. In
  402. other words, if you do manage to kill the thread, your whole process
  403. is likely to be screwed up.
  404. </p><p>
  405. </p><h1><a name="SECTION000600000000000000000">
  406. 5 Non-blocking Sockets</a>
  407. </h1>
  408. <p>
  409. If you've understood the preceeding, you already know most of what you
  410. need to know about the mechanics of using sockets. You'll still use
  411. the same calls, in much the same ways. It's just that, if you do it
  412. right, your app will be almost inside-out.
  413. </p><p>
  414. In Python, you use <code>socket.setblocking(0)</code> to make it
  415. non-blocking. In C, it's more complex, (for one thing, you'll need to
  416. choose between the BSD flavor <code>O_NONBLOCK</code> and the almost
  417. indistinguishable Posix flavor <code>O_NDELAY</code>, which is
  418. completely different from <code>TCP_NODELAY</code>), but it's the
  419. exact same idea. You do this after creating the socket, but before
  420. using it. (Actually, if you're nuts, you can switch back and forth.)
  421. </p><p>
  422. The major mechanical difference is that <code>send</code>,
  423. <code>recv</code>, <code>connect</code> and <code>accept</code> can
  424. return without having done anything. You have (of course) a number of
  425. choices. You can check return code and error codes and generally drive
  426. yourself crazy. If you don't believe me, try it sometime. Your app
  427. will grow large, buggy and suck CPU. So let's skip the brain-dead
  428. solutions and do it right.
  429. </p><p>
  430. Use <code>select</code>.
  431. </p><p>
  432. In C, coding <code>select</code> is fairly complex. In Python, it's a
  433. piece of cake, but it's close enough to the C version that if you
  434. understand <code>select</code> in Python, you'll have little trouble
  435. with it in C.
  436. </p><p>
  437. </p><div class="verbatim"><pre> ready_to_read, ready_to_write, in_error = \\
  438. select.select(
  439. potential_readers,
  440. potential_writers,
  441. potential_errs,
  442. timeout)
  443. </pre></div>
  444. <p>
  445. You pass <code>select</code> three lists: the first contains all
  446. sockets that you might want to try reading; the second all the sockets
  447. you might want to try writing to, and the last (normally left empty)
  448. those that you want to check for errors. You should note that a
  449. socket can go into more than one list. The <code>select</code> call is
  450. blocking, but you can give it a timeout. This is generally a sensible
  451. thing to do - give it a nice long timeout (say a minute) unless you
  452. have good reason to do otherwise.
  453. </p><p>
  454. In return, you will get three lists. They have the sockets that are
  455. actually readable, writable and in error. Each of these lists is a
  456. subset (possbily empty) of the corresponding list you passed in. And
  457. if you put a socket in more than one input list, it will only be (at
  458. most) in one output list.
  459. </p><p>
  460. If a socket is in the output readable list, you can be
  461. as-close-to-certain-as-we-ever-get-in-this-business that a
  462. <code>recv</code> on that socket will return <i>something</i>. Same
  463. idea for the writable list. You'll be able to send
  464. <i>something</i>. Maybe not all you want to, but <i>something</i> is
  465. better than nothing. (Actually, any reasonably healthy socket will
  466. return as writable - it just means outbound network buffer space is
  467. available.)
  468. </p><p>
  469. If you have a "server" socket, put it in the potential_readers
  470. list. If it comes out in the readable list, your <code>accept</code>
  471. will (almost certainly) work. If you have created a new socket to
  472. <code>connect</code> to someone else, put it in the ptoential_writers
  473. list. If it shows up in the writable list, you have a decent chance
  474. that it has connected.
  475. </p><p>
  476. One very nasty problem with <code>select</code>: if somewhere in those
  477. input lists of sockets is one which has died a nasty death, the
  478. <code>select</code> will fail. You then need to loop through every
  479. single damn socket in all those lists and do a
  480. <code>select([sock],[],[],0)</code> until you find the bad one. That
  481. timeout of 0 means it won't take long, but it's ugly.
  482. </p><p>
  483. Actually, <code>select</code> can be handy even with blocking sockets.
  484. It's one way of determining whether you will block - the socket
  485. returns as readable when there's something in the buffers. However,
  486. this still doesn't help with the problem of determining whether the
  487. other end is done, or just busy with something else.
  488. </p><p>
  489. <b>Portability alert</b>: On Unix, <code>select</code> works both with
  490. the sockets and files. Don't try this on Windows. On Windows,
  491. <code>select</code> works with sockets only. Also note that in C, many
  492. of the more advanced socket options are done differently on
  493. Windows. In fact, on Windows I usually use threads (which work very,
  494. very well) with my sockets. Face it, if you want any kind of
  495. performance, your code will look very different on Windows than on
  496. Unix. (I haven't the foggiest how you do this stuff on a Mac.)
  497. </p><p>
  498. </p><h2><a name="SECTION000610000000000000000">
  499. 5.1 Performance</a>
  500. </h2>
  501. <p>
  502. There's no question that the fastest sockets code uses non-blocking
  503. sockets and select to multiplex them. You can put together something
  504. that will saturate a LAN connection without putting any strain on the
  505. CPU. The trouble is that an app written this way can't do much of
  506. anything else - it needs to be ready to shuffle bytes around at all
  507. times.
  508. </p><p>
  509. Assuming that your app is actually supposed to do something more than
  510. that, threading is the optimal solution, (and using non-blocking
  511. sockets will be faster than using blocking sockets). Unfortunately,
  512. threading support in Unixes varies both in API and quality. So the
  513. normal Unix solution is to fork a subprocess to deal with each
  514. connection. The overhead for this is significant (and don't do this on
  515. Windows - the overhead of process creation is enormous there). It also
  516. means that unless each subprocess is completely independent, you'll
  517. need to use another form of IPC, say a pipe, or shared memory and
  518. semaphores, to communicate between the parent and child processes.
  519. </p><p>
  520. Finally, remember that even though blocking sockets are somewhat
  521. slower than non-blocking, in many cases they are the "right"
  522. solution. After all, if your app is driven by the data it receives
  523. over a socket, there's not much sense in complicating the logic just
  524. so your app can wait on <code>select</code> instead of
  525. <code>recv</code>.
  526. </p><p>
  527. </p><h1><a name="SECTION000700000000000000000">
  528. About this document ...</a>
  529. </h1>
  530. <strong>Socket Programming HOWTO</strong>
  531. <p> This document was generated using the <a href="http://saftsack.fs.uni-bayreuth.de/%7Elatex2ht/">
  532. <strong>LaTeX</strong>2<tt>HTML</tt></a> translator.
  533. </p>
  534. <p> <a href="http://saftsack.fs.uni-bayreuth.de/%7Elatex2ht/">
  535. <strong>LaTeX</strong>2<tt>HTML</tt></a> is Copyright Š
  536. 1993, 1994, 1995, 1996, 1997, <a href="http://cbl.leeds.ac.uk/nikos/personal.html">Nikos
  537. Drakos</a>, Computer Based Learning Unit, University of
  538. Leeds, and Copyright Š 1997, 1998, <a href="http://www.maths.mq.edu.au/%7Eross/">Ross
  539. Moore</a>, Mathematics Department, Macquarie University,
  540. Sydney.
  541. </p>
  542. <p> The application of <a href="http://saftsack.fs.uni-bayreuth.de/%7Elatex2ht/">
  543. <strong>LaTeX</strong>2<tt>HTML</tt></a> to the Python
  544. documentation has been heavily tailored by Fred L. Drake,
  545. Jr. Original navigation icons were contributed by Christopher
  546. Petrilli.
  547. </p>
  548. <div class="navigation">
  549. <p></p><hr>
  550. <table align="center" cellpadding="0" cellspacing="2" width="100%">
  551. <tbody><tr>
  552. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  553. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  554. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  555. <td align="center" width="100%">Socket Programming HOWTO</td>
  556. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  557. <td><img src="Socket%20Programming%20HOWTO_files/blank.gif" alt="" border="0" height="32" width="32"></td>
  558. </tr></tbody></table>
  559. <hr>
  560. <span class="release-info">Release 0.00.</span>
  561. </div>
  562. <!--End of Navigation Panel-->
  563. </body></html>