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