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