~dkuhlman/python-training-materials/Materials

« back to all changes in this revision

Viewing changes to python-2.7.12-docs-html/howto/sockets.html

  • Committer: Dave Kuhlman
  • Date: 2017-04-15 16:24:56 UTC
  • Revision ID: dkuhlman@davekuhlman.org-20170415162456-iav9vozzg4iwqwv3
Updated docs

Show diffs side-by-side

added added

removed removed

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