<p>As a complement to the network client tutorial, this tutorial shows how to implement a simple web server in Python. To be sure, this is no substitute for Apache or Zope. There are also more robust ways to implement web services in Python, using modules like BaseHTTPServer. This server uses the socket module exclusively.</p><p>You will recall that the socket module is the backbone of most Python web service modules. As with the simple network client, building a server with it illustrates the basics of web services in Python transparently. BaseHTTPServer itself imports the socket module to affect a server.</p><p>By way of review, All network transactions happen between clients and servers. In most protocols , the clients ask a certain address and receive data.</p><p>Within each address, a multitude of servers can run. The limit is in the hardware. With sufficient hardware (RAM, processor speed, etc.), the same computer can serve as a web server, an ftp server, and mail server (pop, smtp, imap, or all of the above) all at the same time. Each service is associeted with a port. The port is bound to a socket. The server listens to its associated port and gives information when requests are received on that port.</p><p>So to affect a network connection you need to know the host, the port, and the actions allowed on that port. Most web servers run on port 80. However, in order to avoid conflict with an installed Apache server, our web server will run on port 8080. In order to avoid conflict with other services, it is best to keep HTTP services on port 80 or 8080. These are the two most common. Obviously, if these are used, you must find an open port and alert users to the change.</p><p>As with the network client, you should note that these addresses are the common port numbers for the different services. As long as the client asks for the correct service on the right port at the right address, communication will still happen. Google&#39;s mail service, for example, did not initially run on the common port numbers but, because they know how to access their accounts, users can still get their mail.</p><p>Unlike the network client, all variables in the server are hardwired. Any service that is expected to run constantly should not have the variables of its internal logic set at the command line. The only variation on this would be if, for some reason, you wanted the service to run occasionally and on various port numbers. If this were the case, however, you would still be able to watch the system time and change bindings accordingly.</p><p>So our sole import is the socket module.</p><pre><code>\nimport socket\n</code></pre><p>Next, we need to declare a few variables.</p><p>As already mentioned, the server needs to know the host to which it is to be associated and the port on which to listen. For our purposes, we shall have the service apply to any host name at all.</p><pre><code> host &#61; &#39;&#39; \n port &#61; 8080 </code></pre> The port, as mentioned earlier, will be 8080. So note that, if you use this server in conjunction with the network client, you will need to change the port number used in that program.<p>Whether to request information or to serve it, in order to access the Internet, we need to create a socket. The syntax for this call is as follows:</p><pre><code>\n&lt;variable&gt; &#61; socket.socket(&lt;family&gt;, &lt;type&gt;)\n</code></pre><p>The recognised socket families are:</p><ul><li> AF_INET: IPv4 protocols (both TCP and UDP) </li><li> AF_INET6: IPv6 protocols (both TCP and UDP) </li><li> AF_UNIX: UNIX domain protocols </li></ul>The first two are obviously internet protocols. Anything that travels over the internet can be accessed in these families. Many networks still do not run on IPv6. So, unless you know otherwise, it is safest to default to IPv4 and use AF_INET.<p>The socket type refers to the type of communication used through the socket. The five socket types are as follows:</p><ul><li> SOCK_STREAM: a connection-oriented, TCP byte stream </li><li> SOCK_DGRAM: UDP transferral of datagrams (self-contained IP packets that do not rely on client-server confirmation) </li><li> SOCK_RAW: a raw socket </li><li> SOCK_RDM: for reliable datagrams </li><li> SOCK_SEQPACKET: sequential transfer of records over a connection </li></ul>By far, the most common types are SOCK_STEAM and SOCK_DGRAM because they function on the two protocols of the IP suite (TCP and UDP). The latter three are much rarer and so may not always be supported.<p>So let&#39;s create a socket and assign it to a variable.</p><pre><code>\nc &#61; socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n</code></pre><p>After creating the socket, we then need to set the socket options. For any socket object, you can set the socket options by using the setsockopt() method. The syntax is as follows:</p><blockquote>socket_object.setsockopt(level, option_name, value) For our purposes, we use the following line: <pre><code>\nc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n</code></pre><p>The term &#39;level&#39; refers to the categories of options. For socket-level options, use SOL_SOCKET. For protocol numbers, one would use IPPROTO_IP. SOL_SOCKET is a constant attribute of the socket. Exactly which options are available as part of each level are determined by your operating system and whether you are using IPv4 or IPv6.</p><p>The documentation for Linux and related Unix systems can be found in the system documentation. The documentation for Microsoft users can be found on the <a href="http://msdn2.microsoft.com/en-us/library/ms740532.aspx" data-component="link" data-source="inlineLink" data-type="externalLink" data-ordinal="1">MSDN website</a>. As of this writing, I have not found Mac documentation on socket programming. As Mac is roughly based upon BSD Unix, it is likely to implement a full complement of options.</p><p>In order to ensure reusability of this socket, we use the SO_REUSEADDR option. One could restrict the server to only run on open ports, but that seems unnecessary. Do note, however, that if two or more services are deployed on the same port, the effects are unpredictable. One cannot be certain which service will receive which packet of information.</p><p>Finally, the &#39;1&#39; for a value is the value by which the request on the socket is known in the program. In this way, a program can listen on a socket in very nuanced ways.</p></blockquote><p>After creating the socket and setting its options, we need to bind the port to the socket.</p><pre><code>\nc.bind((host, port))\n</code></pre><p>The binding done, we now tell the computer to wait and to listen on that port.</p><pre><code>\nc.listen(1)\n</code></pre><p>If we want to give feedback to the person who calls the server, we could now enter a print command to confirm that the server is up and running.</p><p>Having setup the server, we now need to tell Python what to do when a request is made on the given port. For this we reference the request by its value and use it as the argument of a persistent while loop.</p><p>When a request is made, the server should accept the request and create a file object to interact with it.</p><pre><code> while 1: \n csock, caddr &#61; c.accept() \n cfile &#61; csock.makefile(&#39;rw&#39;, 0) </code></pre><p>In this case, the server uses the same port for reading and writing. Therefore, the makefile method is given an argument &#39;rw&#39;. The null length of the buffer size simply leaves that part of the file to be determined dynamically.</p><p>Unless we want to create a single-action server, the next step is to read input from the file object. When we do that, we should be careful to strip that input of excess whitespace.</p><pre><code> line &#61; cfile.readline().strip() </code></pre><p>The request will come in the form of an action, followed by a page, the protocol, and the version of the protocol being used. If one wants to serve a web page, one splits this input to retrieve the page requested and then reads that page into a variable which is then written to the socket file object. A function for reading a file into a dictionary can be found <a href="https://www.thoughtco.com/python-programming-4133477" data-component="link" data-source="inlineLink" data-type="internalLink" data-ordinal="1">in the blog</a>.</p><p>In order to make this tutorial a bit more illustrative of what one can do with the socket module, we will forego that part of the server and instead show how one can nuance the presentation of data. Enter the next several lines into the program.</p><pre><code> cfile.write(&#39;HTTP/1.0 200 OK\\n\\n&#39;) \n cfile.write(&#39;&lt;html&gt;&lt;head&gt;&lt;title&gt;Welcome %s!&lt;/title&gt;&lt;/head&gt;&#39; %(str(caddr))) \n cfile.write(&#39;&lt;body&gt;&lt;h1&gt;Follow the link...&lt;/h1&gt;&#39;) \n cfile.write(&#39;All the server needs to do is &#39;) \n cfile.write(&#39;to deliver the text to the socket. &#39;) \n cfile.write(&#39;It delivers the HTML code for a link, &#39;) \n cfile.write(&#39;and the web browser converts it. &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&#39;) \n cfile.write(&#39;&lt;font size&#61;&#34;7&#34;&gt;&lt;center&gt; &lt;a href&#61;&#34;http://python.about.com/index.html&#34;&gt;Click me!&lt;/a&gt; &lt;/center&gt;&lt;/font&gt;&#39;) \n cfile.write(&#39;&lt;br&gt;&lt;br&gt;The wording of your request was: &#34;%s&#34;&#39; %(line)) \n cfile.write(&#39;&lt;/body&gt;&lt;/html&gt;&#39;) </code></pre><p>If one is sending a web page, the first line is a nice way of introducing the data to a web browser. If it is left out, most web browsers will default to rendering HTML. However, if one includes it, the &#39;OK&#39; must be followed by <i>two</i> new line characters. These are used to distinguish the protocol information from the page content.</p><p>The syntax of the first line, as you can probably surmise, is protocol, protocol version, message number, and status. If you have ever gone to a web page that has moved, you have probably received a 404 error. The 200 message here is simply the affirmative message.</p><p>The rest of the output is simply a web page broken up over several lines. You will note that the server can be programmed to use user data in the output. The final line reflects the web request as it was received by the server.</p><p>Finally, as the closing acts of the request, we need to close the file object and the server socket.</p><pre><code> cfile.close() \n csock.close() </code></pre> Now save this program under a recognisable name. After you call it with &#39;python program_name.py&#39;, if you programmed a message to confirm the service as running, this should print to the screen. The terminal will then seem to pause. All is as it should be. Open your web browser and go to localhost:8080. You should then see the output of the write commands we gave. Please note that, for the sake of space, I did not implement error handling in this program. However, any program released into the &#39;wild&#39; should. See <a href="https://www.thoughtco.com/what-is-python-2813564" data-component="link" data-source="inlineLink" data-type="internalLink" data-ordinal="1">&#34;Error Handling in Python&#34;</a> for more.