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