sockets.html 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
  6. <meta property="og:title" content="Socket Programming HOWTO" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/howto/sockets.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="Author, Gordon McMillan,. Abstract: Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around. This is a 10,000 foot overview of sockets. It’s not reall..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="Author, Gordon McMillan,. Abstract: Sockets are used nearly everywhere, but are one of the most severely misunderstood technologies around. This is a 10,000 foot overview of sockets. It’s not reall..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>Socket Programming HOWTO &#8212; Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
  21. <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
  22. <script src="../_static/jquery.js"></script>
  23. <script src="../_static/underscore.js"></script>
  24. <script src="../_static/doctools.js"></script>
  25. <script src="../_static/sidebar.js"></script>
  26. <link rel="search" type="application/opensearchdescription+xml"
  27. title="Search within Python 3.12.0 documentation"
  28. href="../_static/opensearch.xml"/>
  29. <link rel="author" title="About these documents" href="../about.html" />
  30. <link rel="index" title="Index" href="../genindex.html" />
  31. <link rel="search" title="Search" href="../search.html" />
  32. <link rel="copyright" title="Copyright" href="../copyright.html" />
  33. <link rel="next" title="Sorting HOW TO" href="sorting.html" />
  34. <link rel="prev" title="Regular Expression HOWTO" href="regex.html" />
  35. <link rel="canonical" href="https://docs.python.org/3/howto/sockets.html" />
  36. <style>
  37. @media only screen {
  38. table.full-width-table {
  39. width: 100%;
  40. }
  41. }
  42. </style>
  43. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  44. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  45. <script type="text/javascript" src="../_static/copybutton.js"></script>
  46. <script type="text/javascript" src="../_static/menu.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">Socket Programming HOWTO</a><ul>
  86. <li><a class="reference internal" href="#sockets">Sockets</a><ul>
  87. <li><a class="reference internal" href="#history">History</a></li>
  88. </ul>
  89. </li>
  90. <li><a class="reference internal" href="#creating-a-socket">Creating a Socket</a><ul>
  91. <li><a class="reference internal" href="#ipc">IPC</a></li>
  92. </ul>
  93. </li>
  94. <li><a class="reference internal" href="#using-a-socket">Using a Socket</a><ul>
  95. <li><a class="reference internal" href="#binary-data">Binary Data</a></li>
  96. </ul>
  97. </li>
  98. <li><a class="reference internal" href="#disconnecting">Disconnecting</a><ul>
  99. <li><a class="reference internal" href="#when-sockets-die">When Sockets Die</a></li>
  100. </ul>
  101. </li>
  102. <li><a class="reference internal" href="#non-blocking-sockets">Non-blocking Sockets</a></li>
  103. </ul>
  104. </li>
  105. </ul>
  106. </div>
  107. <div>
  108. <h4>Previous topic</h4>
  109. <p class="topless"><a href="regex.html"
  110. title="previous chapter">Regular Expression HOWTO</a></p>
  111. </div>
  112. <div>
  113. <h4>Next topic</h4>
  114. <p class="topless"><a href="sorting.html"
  115. title="next chapter">Sorting HOW TO</a></p>
  116. </div>
  117. <div role="note" aria-label="source link">
  118. <h3>This Page</h3>
  119. <ul class="this-page-menu">
  120. <li><a href="../bugs.html">Report a Bug</a></li>
  121. <li>
  122. <a href="https://github.com/python/cpython/blob/main/Doc/howto/sockets.rst"
  123. rel="nofollow">Show Source
  124. </a>
  125. </li>
  126. </ul>
  127. </div>
  128. </nav>
  129. </div>
  130. </div>
  131. <div class="related" role="navigation" aria-label="related navigation">
  132. <h3>Navigation</h3>
  133. <ul>
  134. <li class="right" style="margin-right: 10px">
  135. <a href="../genindex.html" title="General Index"
  136. accesskey="I">index</a></li>
  137. <li class="right" >
  138. <a href="../py-modindex.html" title="Python Module Index"
  139. >modules</a> |</li>
  140. <li class="right" >
  141. <a href="sorting.html" title="Sorting HOW TO"
  142. accesskey="N">next</a> |</li>
  143. <li class="right" >
  144. <a href="regex.html" title="Regular Expression HOWTO"
  145. accesskey="P">previous</a> |</li>
  146. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  147. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  148. <li class="switchers">
  149. <div class="language_switcher_placeholder"></div>
  150. <div class="version_switcher_placeholder"></div>
  151. </li>
  152. <li>
  153. </li>
  154. <li id="cpython-language-and-version">
  155. <a href="../index.html">3.12.0 Documentation</a> &#187;
  156. </li>
  157. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li>
  158. <li class="nav-item nav-item-this"><a href="">Socket Programming HOWTO</a></li>
  159. <li class="right">
  160. <div class="inline-search" role="search">
  161. <form class="inline-search" action="../search.html" method="get">
  162. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  163. <input type="submit" value="Go" />
  164. </form>
  165. </div>
  166. |
  167. </li>
  168. <li class="right">
  169. <label class="theme-selector-label">
  170. Theme
  171. <select class="theme-selector" oninput="activateTheme(this.value)">
  172. <option value="auto" selected>Auto</option>
  173. <option value="light">Light</option>
  174. <option value="dark">Dark</option>
  175. </select>
  176. </label> |</li>
  177. </ul>
  178. </div>
  179. <div class="document">
  180. <div class="documentwrapper">
  181. <div class="bodywrapper">
  182. <div class="body" role="main">
  183. <section id="socket-programming-howto">
  184. <span id="socket-howto"></span><h1>Socket Programming HOWTO<a class="headerlink" href="#socket-programming-howto" title="Permalink to this headline">¶</a></h1>
  185. <dl class="field-list simple">
  186. <dt class="field-odd">Author</dt>
  187. <dd class="field-odd"><p>Gordon McMillan</p>
  188. </dd>
  189. </dl>
  190. <div class="topic">
  191. <p class="topic-title">Abstract</p>
  192. <p>Sockets are used nearly everywhere, but are one of the most severely
  193. misunderstood technologies around. This is a 10,000 foot overview of sockets.
  194. It’s not really a tutorial - you’ll still have work to do in getting things
  195. operational. It doesn’t cover the fine points (and there are a lot of them), but
  196. I hope it will give you enough background to begin using them decently.</p>
  197. </div>
  198. <section id="sockets">
  199. <h2>Sockets<a class="headerlink" href="#sockets" title="Permalink to this headline">¶</a></h2>
  200. <p>I’m only going to talk about INET (i.e. IPv4) sockets, but they account for at least 99% of
  201. the sockets in use. And I’ll only talk about STREAM (i.e. TCP) sockets - unless you really
  202. know what you’re doing (in which case this HOWTO isn’t for you!), you’ll get
  203. better behavior and performance from a STREAM socket than anything else. I will
  204. try to clear up the mystery of what a socket is, as well as some hints on how to
  205. work with blocking and non-blocking sockets. But I’ll start by talking about
  206. blocking sockets. You’ll need to know how they work before dealing with
  207. non-blocking sockets.</p>
  208. <p>Part of the trouble with understanding these things is that “socket” can mean a
  209. number of subtly different things, depending on context. So first, let’s make a
  210. distinction between a “client” socket - an endpoint of a conversation, and a
  211. “server” socket, which is more like a switchboard operator. The client
  212. application (your browser, for example) uses “client” sockets exclusively; the
  213. web server it’s talking to uses both “server” sockets and “client” sockets.</p>
  214. <section id="history">
  215. <h3>History<a class="headerlink" href="#history" title="Permalink to this headline">¶</a></h3>
  216. <p>Of the various forms of <abbr title="Inter Process Communication">IPC</abbr>,
  217. sockets are by far the most popular. On any given platform, there are
  218. likely to be other forms of IPC that are faster, but for
  219. cross-platform communication, sockets are about the only game in town.</p>
  220. <p>They were invented in Berkeley as part of the BSD flavor of Unix. They spread
  221. like wildfire with the internet. With good reason — the combination of sockets
  222. with INET makes talking to arbitrary machines around the world unbelievably easy
  223. (at least compared to other schemes).</p>
  224. </section>
  225. </section>
  226. <section id="creating-a-socket">
  227. <h2>Creating a Socket<a class="headerlink" href="#creating-a-socket" title="Permalink to this headline">¶</a></h2>
  228. <p>Roughly speaking, when you clicked on the link that brought you to this page,
  229. your browser did something like the following:</p>
  230. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># create an INET, STREAMing socket</span>
  231. <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><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>
  232. <span class="c1"># now connect to the web server on port 80 - the normal http port</span>
  233. <span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="s2">&quot;www.python.org&quot;</span><span class="p">,</span> <span class="mi">80</span><span class="p">))</span>
  234. </pre></div>
  235. </div>
  236. <p>When the <code class="docutils literal notranslate"><span class="pre">connect</span></code> completes, the socket <code class="docutils literal notranslate"><span class="pre">s</span></code> can be used to send
  237. in a request for the text of the page. The same socket will read the
  238. reply, and then be destroyed. That’s right, destroyed. Client sockets
  239. are normally only used for one exchange (or a small set of sequential
  240. exchanges).</p>
  241. <p>What happens in the web server is a bit more complex. First, the web server
  242. creates a “server socket”:</p>
  243. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># create an INET, STREAMing socket</span>
  244. <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><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>
  245. <span class="c1"># bind the socket to a public host, and a well-known port</span>
  246. <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>
  247. <span class="c1"># become a server socket</span>
  248. <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>
  249. </pre></div>
  250. </div>
  251. <p>A couple things to notice: we used <code class="docutils literal notranslate"><span class="pre">socket.gethostname()</span></code> so that the socket
  252. would be visible to the outside world. If we had used <code class="docutils literal notranslate"><span class="pre">s.bind(('localhost',</span>
  253. <span class="pre">80))</span></code> or <code class="docutils literal notranslate"><span class="pre">s.bind(('127.0.0.1',</span> <span class="pre">80))</span></code> we would still have a “server” socket,
  254. but one that was only visible within the same machine. <code class="docutils literal notranslate"><span class="pre">s.bind(('',</span> <span class="pre">80))</span></code>
  255. specifies that the socket is reachable by any address the machine happens to
  256. have.</p>
  257. <p>A second thing to note: low number ports are usually reserved for “well known”
  258. services (HTTP, SNMP etc). If you’re playing around, use a nice high number (4
  259. digits).</p>
  260. <p>Finally, the argument to <code class="docutils literal notranslate"><span class="pre">listen</span></code> tells the socket library that we want it to
  261. queue up as many as 5 connect requests (the normal max) before refusing outside
  262. connections. If the rest of the code is written properly, that should be plenty.</p>
  263. <p>Now that we have a “server” socket, listening on port 80, we can enter the
  264. mainloop of the web server:</p>
  265. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
  266. <span class="c1"># accept connections from outside</span>
  267. <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>
  268. <span class="c1"># now do something with the clientsocket</span>
  269. <span class="c1"># in this case, we&#39;ll pretend this is a threaded server</span>
  270. <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>
  271. <span class="n">ct</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
  272. </pre></div>
  273. </div>
  274. <p>There’s actually 3 general ways in which this loop could work - dispatching a
  275. thread to handle <code class="docutils literal notranslate"><span class="pre">clientsocket</span></code>, create a new process to handle
  276. <code class="docutils literal notranslate"><span class="pre">clientsocket</span></code>, or restructure this app to use non-blocking sockets, and
  277. multiplex between our “server” socket and any active <code class="docutils literal notranslate"><span class="pre">clientsocket</span></code>s using
  278. <code class="docutils literal notranslate"><span class="pre">select</span></code>. More about that later. The important thing to understand now is
  279. this: this is <em>all</em> a “server” socket does. It doesn’t send any data. It doesn’t
  280. receive any data. It just produces “client” sockets. Each <code class="docutils literal notranslate"><span class="pre">clientsocket</span></code> is
  281. created in response to some <em>other</em> “client” socket doing a <code class="docutils literal notranslate"><span class="pre">connect()</span></code> to the
  282. host and port we’re bound to. As soon as we’ve created that <code class="docutils literal notranslate"><span class="pre">clientsocket</span></code>, we
  283. go back to listening for more connections. The two “clients” are free to chat it
  284. up - they are using some dynamically allocated port which will be recycled when
  285. the conversation ends.</p>
  286. <section id="ipc">
  287. <h3>IPC<a class="headerlink" href="#ipc" title="Permalink to this headline">¶</a></h3>
  288. <p>If you need fast IPC between two processes on one machine, you should look into
  289. pipes or shared memory. If you do decide to use AF_INET sockets, bind the
  290. “server” socket to <code class="docutils literal notranslate"><span class="pre">'localhost'</span></code>. On most platforms, this will take a
  291. shortcut around a couple of layers of network code and be quite a bit faster.</p>
  292. <div class="admonition seealso">
  293. <p class="admonition-title">See also</p>
  294. <p>The <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> integrates cross-platform IPC into a higher-level
  295. API.</p>
  296. </div>
  297. </section>
  298. </section>
  299. <section id="using-a-socket">
  300. <h2>Using a Socket<a class="headerlink" href="#using-a-socket" title="Permalink to this headline">¶</a></h2>
  301. <p>The first thing to note, is that the web browser’s “client” socket and the web
  302. server’s “client” socket are identical beasts. That is, this is a “peer to peer”
  303. conversation. Or to put it another way, <em>as the designer, you will have to
  304. decide what the rules of etiquette are for a conversation</em>. Normally, the
  305. <code class="docutils literal notranslate"><span class="pre">connect</span></code>ing socket starts the conversation, by sending in a request, or
  306. perhaps a signon. But that’s a design decision - it’s not a rule of sockets.</p>
  307. <p>Now there are two sets of verbs to use for communication. You can use <code class="docutils literal notranslate"><span class="pre">send</span></code>
  308. and <code class="docutils literal notranslate"><span class="pre">recv</span></code>, or you can transform your client socket into a file-like beast and
  309. use <code class="docutils literal notranslate"><span class="pre">read</span></code> and <code class="docutils literal notranslate"><span class="pre">write</span></code>. The latter is the way Java presents its sockets.
  310. I’m not going to talk about it here, except to warn you that you need to use
  311. <code class="docutils literal notranslate"><span class="pre">flush</span></code> on sockets. These are buffered “files”, and a common mistake is to
  312. <code class="docutils literal notranslate"><span class="pre">write</span></code> something, and then <code class="docutils literal notranslate"><span class="pre">read</span></code> for a reply. Without a <code class="docutils literal notranslate"><span class="pre">flush</span></code> in
  313. there, you may wait forever for the reply, because the request may still be in
  314. your output buffer.</p>
  315. <p>Now we come to the major stumbling block of sockets - <code class="docutils literal notranslate"><span class="pre">send</span></code> and <code class="docutils literal notranslate"><span class="pre">recv</span></code> operate
  316. on the network buffers. They do not necessarily handle all the bytes you hand
  317. them (or expect from them), because their major focus is handling the network
  318. buffers. In general, they return when the associated network buffers have been
  319. filled (<code class="docutils literal notranslate"><span class="pre">send</span></code>) or emptied (<code class="docutils literal notranslate"><span class="pre">recv</span></code>). They then tell you how many bytes they
  320. handled. It is <em>your</em> responsibility to call them again until your message has
  321. been completely dealt with.</p>
  322. <p>When a <code class="docutils literal notranslate"><span class="pre">recv</span></code> returns 0 bytes, it means the other side has closed (or is in
  323. the process of closing) the connection. You will not receive any more data on
  324. this connection. Ever. You may be able to send data successfully; I’ll talk
  325. more about this later.</p>
  326. <p>A protocol like HTTP uses a socket for only one transfer. The client sends a
  327. request, then reads a reply. That’s it. The socket is discarded. This means that
  328. a client can detect the end of the reply by receiving 0 bytes.</p>
  329. <p>But if you plan to reuse your socket for further transfers, you need to realize
  330. that <em>there is no</em> <abbr title="End of Transfer">EOT</abbr> <em>on a socket.</em> I repeat: if a socket
  331. <code class="docutils literal notranslate"><span class="pre">send</span></code> or <code class="docutils literal notranslate"><span class="pre">recv</span></code> returns after handling 0 bytes, the connection has been
  332. broken. If the connection has <em>not</em> been broken, you may wait on a <code class="docutils literal notranslate"><span class="pre">recv</span></code>
  333. forever, because the socket will <em>not</em> tell you that there’s nothing more to
  334. read (for now). Now if you think about that a bit, you’ll come to realize a
  335. fundamental truth of sockets: <em>messages must either be fixed length</em> (yuck), <em>or
  336. be delimited</em> (shrug), <em>or indicate how long they are</em> (much better), <em>or end by
  337. shutting down the connection</em>. The choice is entirely yours, (but some ways are
  338. righter than others).</p>
  339. <p>Assuming you don’t want to end the connection, the simplest solution is a fixed
  340. length message:</p>
  341. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MySocket</span><span class="p">:</span>
  342. <span class="w"> </span><span class="sd">&quot;&quot;&quot;demonstration class only</span>
  343. <span class="sd"> - coded for clarity, not efficiency</span>
  344. <span class="sd"> &quot;&quot;&quot;</span>
  345. <span class="k">def</span> <span class="fm">__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="kc">None</span><span class="p">):</span>
  346. <span class="k">if</span> <span class="n">sock</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
  347. <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>
  348. <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>
  349. <span class="k">else</span><span class="p">:</span>
  350. <span class="bp">self</span><span class="o">.</span><span class="n">sock</span> <span class="o">=</span> <span class="n">sock</span>
  351. <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>
  352. <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>
  353. <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>
  354. <span class="n">totalsent</span> <span class="o">=</span> <span class="mi">0</span>
  355. <span class="k">while</span> <span class="n">totalsent</span> <span class="o">&lt;</span> <span class="n">MSGLEN</span><span class="p">:</span>
  356. <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>
  357. <span class="k">if</span> <span class="n">sent</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
  358. <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>
  359. <span class="n">totalsent</span> <span class="o">=</span> <span class="n">totalsent</span> <span class="o">+</span> <span class="n">sent</span>
  360. <span class="k">def</span> <span class="nf">myreceive</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  361. <span class="n">chunks</span> <span class="o">=</span> <span class="p">[]</span>
  362. <span class="n">bytes_recd</span> <span class="o">=</span> <span class="mi">0</span>
  363. <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>
  364. <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>
  365. <span class="k">if</span> <span class="n">chunk</span> <span class="o">==</span> <span class="sa">b</span><span class="s1">&#39;&#39;</span><span class="p">:</span>
  366. <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>
  367. <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>
  368. <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>
  369. <span class="k">return</span> <span class="sa">b</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>
  370. </pre></div>
  371. </div>
  372. <p>The sending code here is usable for almost any messaging scheme - in Python you
  373. send strings, and you can use <code class="docutils literal notranslate"><span class="pre">len()</span></code> to determine its length (even if it has
  374. embedded <code class="docutils literal notranslate"><span class="pre">\0</span></code> characters). It’s mostly the receiving code that gets more
  375. complex. (And in C, it’s not much worse, except you can’t use <code class="docutils literal notranslate"><span class="pre">strlen</span></code> if the
  376. message has embedded <code class="docutils literal notranslate"><span class="pre">\0</span></code>s.)</p>
  377. <p>The easiest enhancement is to make the first character of the message an
  378. indicator of message type, and have the type determine the length. Now you have
  379. two <code class="docutils literal notranslate"><span class="pre">recv</span></code>s - the first to get (at least) that first character so you can
  380. look up the length, and the second in a loop to get the rest. If you decide to
  381. go the delimited route, you’ll be receiving in some arbitrary chunk size, (4096
  382. or 8192 is frequently a good match for network buffer sizes), and scanning what
  383. you’ve received for a delimiter.</p>
  384. <p>One complication to be aware of: if your conversational protocol allows multiple
  385. messages to be sent back to back (without some kind of reply), and you pass
  386. <code class="docutils literal notranslate"><span class="pre">recv</span></code> an arbitrary chunk size, you may end up reading the start of a
  387. following message. You’ll need to put that aside and hold onto it, until it’s
  388. needed.</p>
  389. <p>Prefixing the message with its length (say, as 5 numeric characters) gets more
  390. complex, because (believe it or not), you may not get all 5 characters in one
  391. <code class="docutils literal notranslate"><span class="pre">recv</span></code>. In playing around, you’ll get away with it; but in high network loads,
  392. your code will very quickly break unless you use two <code class="docutils literal notranslate"><span class="pre">recv</span></code> loops - the first
  393. to determine the length, the second to get the data part of the message. Nasty.
  394. This is also when you’ll discover that <code class="docutils literal notranslate"><span class="pre">send</span></code> does not always manage to get
  395. rid of everything in one pass. And despite having read this, you will eventually
  396. get bit by it!</p>
  397. <p>In the interests of space, building your character, (and preserving my
  398. competitive position), these enhancements are left as an exercise for the
  399. reader. Lets move on to cleaning up.</p>
  400. <section id="binary-data">
  401. <h3>Binary Data<a class="headerlink" href="#binary-data" title="Permalink to this headline">¶</a></h3>
  402. <p>It is perfectly possible to send binary data over a socket. The major problem is
  403. that not all machines use the same formats for binary data. For example,
  404. <a class="reference external" href="https://en.wikipedia.org/wiki/Endianness#Networking">network byte order</a>
  405. is big-endian, with the most significant byte first,
  406. so a 16 bit integer with the value <code class="docutils literal notranslate"><span class="pre">1</span></code> would be the two hex bytes <code class="docutils literal notranslate"><span class="pre">00</span> <span class="pre">01</span></code>.
  407. However, most common processors (x86/AMD64, ARM, RISC-V), are little-endian,
  408. with the least significant byte first - that same <code class="docutils literal notranslate"><span class="pre">1</span></code> would be <code class="docutils literal notranslate"><span class="pre">01</span> <span class="pre">00</span></code>.</p>
  409. <p>Socket libraries have calls for converting 16 and 32 bit integers - <code class="docutils literal notranslate"><span class="pre">ntohl,</span>
  410. <span class="pre">htonl,</span> <span class="pre">ntohs,</span> <span class="pre">htons</span></code> where “n” means <em>network</em> and “h” means <em>host</em>, “s” means
  411. <em>short</em> and “l” means <em>long</em>. Where network order is host order, these do
  412. nothing, but where the machine is byte-reversed, these swap the bytes around
  413. appropriately.</p>
  414. <p>In these days of 64-bit machines, the ASCII representation of binary data is
  415. frequently smaller than the binary representation. That’s because a surprising
  416. amount of the time, most integers have the value 0, or maybe 1.
  417. The string <code class="docutils literal notranslate"><span class="pre">&quot;0&quot;</span></code> would be two bytes, while a full 64-bit integer would be 8.
  418. Of course, this doesn’t fit well with fixed-length messages.
  419. Decisions, decisions.</p>
  420. </section>
  421. </section>
  422. <section id="disconnecting">
  423. <h2>Disconnecting<a class="headerlink" href="#disconnecting" title="Permalink to this headline">¶</a></h2>
  424. <p>Strictly speaking, you’re supposed to use <code class="docutils literal notranslate"><span class="pre">shutdown</span></code> on a socket before you
  425. <code class="docutils literal notranslate"><span class="pre">close</span></code> it. The <code class="docutils literal notranslate"><span class="pre">shutdown</span></code> is an advisory to the socket at the other end.
  426. Depending on the argument you pass it, it can mean “I’m not going to send
  427. anymore, but I’ll still listen”, or “I’m not listening, good riddance!”. Most
  428. socket libraries, however, are so used to programmers neglecting to use this
  429. piece of etiquette that normally a <code class="docutils literal notranslate"><span class="pre">close</span></code> is the same as <code class="docutils literal notranslate"><span class="pre">shutdown();</span>
  430. <span class="pre">close()</span></code>. So in most situations, an explicit <code class="docutils literal notranslate"><span class="pre">shutdown</span></code> is not needed.</p>
  431. <p>One way to use <code class="docutils literal notranslate"><span class="pre">shutdown</span></code> effectively is in an HTTP-like exchange. The client
  432. sends a request and then does a <code class="docutils literal notranslate"><span class="pre">shutdown(1)</span></code>. This tells the server “This
  433. client is done sending, but can still receive.” The server can detect “EOF” by
  434. a receive of 0 bytes. It can assume it has the complete request. The server
  435. sends a reply. If the <code class="docutils literal notranslate"><span class="pre">send</span></code> completes successfully then, indeed, the client
  436. was still receiving.</p>
  437. <p>Python takes the automatic shutdown a step further, and says that when a socket
  438. is garbage collected, it will automatically do a <code class="docutils literal notranslate"><span class="pre">close</span></code> if it’s needed. But
  439. relying on this is a very bad habit. If your socket just disappears without
  440. doing a <code class="docutils literal notranslate"><span class="pre">close</span></code>, the socket at the other end may hang indefinitely, thinking
  441. you’re just being slow. <em>Please</em> <code class="docutils literal notranslate"><span class="pre">close</span></code> your sockets when you’re done.</p>
  442. <section id="when-sockets-die">
  443. <h3>When Sockets Die<a class="headerlink" href="#when-sockets-die" title="Permalink to this headline">¶</a></h3>
  444. <p>Probably the worst thing about using blocking sockets is what happens when the
  445. other side comes down hard (without doing a <code class="docutils literal notranslate"><span class="pre">close</span></code>). Your socket is likely to
  446. hang. TCP is a reliable protocol, and it will wait a long, long time
  447. before giving up on a connection. If you’re using threads, the entire thread is
  448. essentially dead. There’s not much you can do about it. As long as you aren’t
  449. doing something dumb, like holding a lock while doing a blocking read, the
  450. thread isn’t really consuming much in the way of resources. Do <em>not</em> try to kill
  451. the thread - part of the reason that threads are more efficient than processes
  452. is that they avoid the overhead associated with the automatic recycling of
  453. resources. In other words, if you do manage to kill the thread, your whole
  454. process is likely to be screwed up.</p>
  455. </section>
  456. </section>
  457. <section id="non-blocking-sockets">
  458. <h2>Non-blocking Sockets<a class="headerlink" href="#non-blocking-sockets" title="Permalink to this headline">¶</a></h2>
  459. <p>If you’ve understood the preceding, you already know most of what you need to
  460. know about the mechanics of using sockets. You’ll still use the same calls, in
  461. much the same ways. It’s just that, if you do it right, your app will be almost
  462. inside-out.</p>
  463. <p>In Python, you use <code class="docutils literal notranslate"><span class="pre">socket.setblocking(False)</span></code> to make it non-blocking. In C, it’s
  464. more complex, (for one thing, you’ll need to choose between the BSD flavor
  465. <code class="docutils literal notranslate"><span class="pre">O_NONBLOCK</span></code> and the almost indistinguishable POSIX flavor <code class="docutils literal notranslate"><span class="pre">O_NDELAY</span></code>, which
  466. is completely different from <code class="docutils literal notranslate"><span class="pre">TCP_NODELAY</span></code>), but it’s the exact same idea. You
  467. do this after creating the socket, but before using it. (Actually, if you’re
  468. nuts, you can switch back and forth.)</p>
  469. <p>The major mechanical difference is that <code class="docutils literal notranslate"><span class="pre">send</span></code>, <code class="docutils literal notranslate"><span class="pre">recv</span></code>, <code class="docutils literal notranslate"><span class="pre">connect</span></code> and
  470. <code class="docutils literal notranslate"><span class="pre">accept</span></code> can return without having done anything. You have (of course) a
  471. number of choices. You can check return code and error codes and generally drive
  472. yourself crazy. If you don’t believe me, try it sometime. Your app will grow
  473. large, buggy and suck CPU. So let’s skip the brain-dead solutions and do it
  474. right.</p>
  475. <p>Use <code class="docutils literal notranslate"><span class="pre">select</span></code>.</p>
  476. <p>In C, coding <code class="docutils literal notranslate"><span class="pre">select</span></code> is fairly complex. In Python, it’s a piece of cake, but
  477. it’s close enough to the C version that if you understand <code class="docutils literal notranslate"><span class="pre">select</span></code> in Python,
  478. you’ll have little trouble with it in C:</p>
  479. <div class="highlight-python3 notranslate"><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> \
  480. <span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">(</span>
  481. <span class="n">potential_readers</span><span class="p">,</span>
  482. <span class="n">potential_writers</span><span class="p">,</span>
  483. <span class="n">potential_errs</span><span class="p">,</span>
  484. <span class="n">timeout</span><span class="p">)</span>
  485. </pre></div>
  486. </div>
  487. <p>You pass <code class="docutils literal notranslate"><span class="pre">select</span></code> three lists: the first contains all sockets that you might
  488. want to try reading; the second all the sockets you might want to try writing
  489. to, and the last (normally left empty) those that you want to check for errors.
  490. You should note that a socket can go into more than one list. The <code class="docutils literal notranslate"><span class="pre">select</span></code>
  491. call is blocking, but you can give it a timeout. This is generally a sensible
  492. thing to do - give it a nice long timeout (say a minute) unless you have good
  493. reason to do otherwise.</p>
  494. <p>In return, you will get three lists. They contain the sockets that are actually
  495. readable, writable and in error. Each of these lists is a subset (possibly
  496. empty) of the corresponding list you passed in.</p>
  497. <p>If a socket is in the output readable list, you can be
  498. as-close-to-certain-as-we-ever-get-in-this-business that a <code class="docutils literal notranslate"><span class="pre">recv</span></code> on that
  499. socket will return <em>something</em>. Same idea for the writable list. You’ll be able
  500. to send <em>something</em>. Maybe not all you want to, but <em>something</em> is better than
  501. nothing. (Actually, any reasonably healthy socket will return as writable - it
  502. just means outbound network buffer space is available.)</p>
  503. <p>If you have a “server” socket, put it in the potential_readers list. If it comes
  504. out in the readable list, your <code class="docutils literal notranslate"><span class="pre">accept</span></code> will (almost certainly) work. If you
  505. have created a new socket to <code class="docutils literal notranslate"><span class="pre">connect</span></code> to someone else, put it in the
  506. potential_writers list. If it shows up in the writable list, you have a decent
  507. chance that it has connected.</p>
  508. <p>Actually, <code class="docutils literal notranslate"><span class="pre">select</span></code> can be handy even with blocking sockets. It’s one way of
  509. determining whether you will block - the socket returns as readable when there’s
  510. something in the buffers. However, this still doesn’t help with the problem of
  511. determining whether the other end is done, or just busy with something else.</p>
  512. <p><strong>Portability alert</strong>: On Unix, <code class="docutils literal notranslate"><span class="pre">select</span></code> works both with the sockets and
  513. files. Don’t try this on Windows. On Windows, <code class="docutils literal notranslate"><span class="pre">select</span></code> works with sockets
  514. only. Also note that in C, many of the more advanced socket options are done
  515. differently on Windows. In fact, on Windows I usually use threads (which work
  516. very, very well) with my sockets.</p>
  517. </section>
  518. </section>
  519. <div class="clearer"></div>
  520. </div>
  521. </div>
  522. </div>
  523. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  524. <div class="sphinxsidebarwrapper">
  525. <div>
  526. <h3><a href="../contents.html">Table of Contents</a></h3>
  527. <ul>
  528. <li><a class="reference internal" href="#">Socket Programming HOWTO</a><ul>
  529. <li><a class="reference internal" href="#sockets">Sockets</a><ul>
  530. <li><a class="reference internal" href="#history">History</a></li>
  531. </ul>
  532. </li>
  533. <li><a class="reference internal" href="#creating-a-socket">Creating a Socket</a><ul>
  534. <li><a class="reference internal" href="#ipc">IPC</a></li>
  535. </ul>
  536. </li>
  537. <li><a class="reference internal" href="#using-a-socket">Using a Socket</a><ul>
  538. <li><a class="reference internal" href="#binary-data">Binary Data</a></li>
  539. </ul>
  540. </li>
  541. <li><a class="reference internal" href="#disconnecting">Disconnecting</a><ul>
  542. <li><a class="reference internal" href="#when-sockets-die">When Sockets Die</a></li>
  543. </ul>
  544. </li>
  545. <li><a class="reference internal" href="#non-blocking-sockets">Non-blocking Sockets</a></li>
  546. </ul>
  547. </li>
  548. </ul>
  549. </div>
  550. <div>
  551. <h4>Previous topic</h4>
  552. <p class="topless"><a href="regex.html"
  553. title="previous chapter">Regular Expression HOWTO</a></p>
  554. </div>
  555. <div>
  556. <h4>Next topic</h4>
  557. <p class="topless"><a href="sorting.html"
  558. title="next chapter">Sorting HOW TO</a></p>
  559. </div>
  560. <div role="note" aria-label="source link">
  561. <h3>This Page</h3>
  562. <ul class="this-page-menu">
  563. <li><a href="../bugs.html">Report a Bug</a></li>
  564. <li>
  565. <a href="https://github.com/python/cpython/blob/main/Doc/howto/sockets.rst"
  566. rel="nofollow">Show Source
  567. </a>
  568. </li>
  569. </ul>
  570. </div>
  571. </div>
  572. </div>
  573. <div class="clearer"></div>
  574. </div>
  575. <div class="related" role="navigation" aria-label="related navigation">
  576. <h3>Navigation</h3>
  577. <ul>
  578. <li class="right" style="margin-right: 10px">
  579. <a href="../genindex.html" title="General Index"
  580. >index</a></li>
  581. <li class="right" >
  582. <a href="../py-modindex.html" title="Python Module Index"
  583. >modules</a> |</li>
  584. <li class="right" >
  585. <a href="sorting.html" title="Sorting HOW TO"
  586. >next</a> |</li>
  587. <li class="right" >
  588. <a href="regex.html" title="Regular Expression HOWTO"
  589. >previous</a> |</li>
  590. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  591. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  592. <li class="switchers">
  593. <div class="language_switcher_placeholder"></div>
  594. <div class="version_switcher_placeholder"></div>
  595. </li>
  596. <li>
  597. </li>
  598. <li id="cpython-language-and-version">
  599. <a href="../index.html">3.12.0 Documentation</a> &#187;
  600. </li>
  601. <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li>
  602. <li class="nav-item nav-item-this"><a href="">Socket Programming HOWTO</a></li>
  603. <li class="right">
  604. <div class="inline-search" role="search">
  605. <form class="inline-search" action="../search.html" method="get">
  606. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  607. <input type="submit" value="Go" />
  608. </form>
  609. </div>
  610. |
  611. </li>
  612. <li class="right">
  613. <label class="theme-selector-label">
  614. Theme
  615. <select class="theme-selector" oninput="activateTheme(this.value)">
  616. <option value="auto" selected>Auto</option>
  617. <option value="light">Light</option>
  618. <option value="dark">Dark</option>
  619. </select>
  620. </label> |</li>
  621. </ul>
  622. </div>
  623. <div class="footer">
  624. &copy; <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
  625. <br />
  626. This page is licensed under the Python Software Foundation License Version 2.
  627. <br />
  628. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  629. <br />
  630. See <a href="/license.html">History and License</a> for more information.<br />
  631. <br />
  632. The Python Software Foundation is a non-profit corporation.
  633. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  634. <br />
  635. <br />
  636. Last updated on Oct 02, 2023.
  637. <a href="/bugs.html">Found a bug</a>?
  638. <br />
  639. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
  640. </div>
  641. </body>
  642. </html>