{"id":2048,"date":"2016-03-03T01:07:54","date_gmt":"2016-03-02T19:37:54","guid":{"rendered":"https:\/\/techbeamers.com\/?p=2048"},"modified":"2025-11-30T10:50:59","modified_gmt":"2025-11-30T15:50:59","slug":"python-tutorial-write-tcp-server","status":"publish","type":"post","link":"https:\/\/techbeamers.com\/python-tutorial-write-tcp-server\/","title":{"rendered":"Python Socket: Create a TCP Server-Client"},"content":{"rendered":"\n<p>Python is one of the most popular object-oriented scripting languages with a programmer-friendly syntax and a vast developer community.&nbsp;This tutorial explains the concept of networking programming with the help of Python classes. Here, we&#8217;ll showcase&nbsp;how to write a TCP server and client in Python and implement them using classes.<\/p>\n\n\n\n<p>In&nbsp;our previous Python socket programming tutorials, we&#8217;ve already explained&nbsp;the bit-by-bit details of sockets and writing a socket server\/client application. Hence, we&#8217;ll keep our focus only on the workflow and example code of the Python TCP server and client.<\/p>\n\n\n\n<p>The sample contains the source code for a TCP server and client. For practice, you can extend it to build a small chat&nbsp;system or a local attendance tracking system.<\/p>\n\n\n\n<ul class=\"wp-block-yoast-seo-related-links\"><li>Discover <a href=\"https:\/\/techbeamers.com\/terminal-commands-linux-mac-osx\/\" target=\"_blank\" rel=\"noreferrer noopener\">50+ Terminal Commands for Beginners on Linux\/OS X<\/a><\/li><\/ul>\n\n\n\n<p>If you are new to socket programming, then you would certainly benefit from reading from the below Python tutorials.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-create-tcp-server-and-client-in-python\">Create TCP Server and Client in Python<\/h2>\n\n\n\n<p>To understand the topic in detail, let&#8217;s first have a quick look at the socket classes present in the Python <em><strong>SocketServer<\/strong><\/em> module.&nbsp;It is a framework that wraps the Python socket functionality. For your note, this&nbsp;component has a new name <em><strong><code>socketserver<\/code>&nbsp;<\/strong><\/em>in Python 3.<\/p>\n\n\n<div class=\"wp-block-image wp-image-4958 size-medium\">\n<figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"300\" height=\"300\" src=\"\/wp-content\/uploads\/2016\/03\/Implement-a-TCP-Server-and-Client-Using-Socket-Class-in-Python-300x300.png\" alt=\"Implement a TCP Server and Client Using Socket Class in Python\" class=\"wp-image-4958\"\/><figcaption class=\"wp-element-caption\"><strong><span style=\"font-family: 'trebuchet ms', geneva, sans-serif; font-size: 8pt;\">TCP Server and Client Program in Python.<\/span><\/strong><\/figcaption><\/figure>\n<\/div>\n\n\n<p>There are two types of built-in classes in the <code><em><strong>socketserver<\/strong><\/em><\/code> module.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-synchronous-socket-entities\">Synchronous socket entities<\/h3>\n\n\n\n<p><strong>TCPServer class &#8211;<\/strong> It follows the (Internet) TCP protocol that allows continuous streams of data between the server and client.<\/p>\n\n\n\n<p><strong>UDPServer class &#8211;<\/strong> It makes use of datagrams that contains discrete packets of information. They may go out of order or get dropped in transit.<\/p>\n\n\n\n<p><strong>UnixStreamServer And UnixDatagramServer classes &#8211;<\/strong> These classes are similar to the TCP and UDP classes but use Unix domain sockets. Both of them don&#8217;t support non-Unix platforms.<\/p>\n\n\n\n<p>The above four classes process the calls synchronously; they accept\u00a0and treat the requests in a strict sequence. This behavior doesn&#8217;t scale if each call takes a long time to complete. It returns a lot of data that the client is not able to process instantly.<\/p>\n\n\n\n<p>The solution is to allow multiple threads to take care of each request. Below is the list of classes to manage each connection on separate threads.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-asynchronous-socket-entities\">Asynchronous socket entities<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>ForkingMixIn class<\/li>\n\n\n\n<li>ThreadingMixIn class<\/li>\n<\/ul>\n\n\n\n<p>The <code><strong>socketserver<\/strong><\/code> module has more classes to handle sockets, but we&#8217;ve&nbsp;mentioned the most relevant ones to the topic.<\/p>\n\n\n\n<p>Now let&#8217;s see the example of the Python TCP Server.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-python-tcp-server-py\">Python-TCP-Server.py<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">import socketserver\n\nclass Handler_TCPServer(socketserver.BaseRequestHandler):\n    \"\"\"\n    The TCP Server class for demonstration.\n\n    Note: We need to implement the Handle method to exchange data\n    with TCP client.\n\n    \"\"\"\n\n    def handle(self):\n        # self.request - TCP socket connected to the client\n        self.data = self.request.recv(1024).strip()\n        print(\"{} sent:\".format(self.client_address[0]))\n        print(self.data)\n        # just send back ACK for data arrival confirmation\n        self.request.sendall(\"ACK from TCP Server\".encode())\n\nif __name__ == \"__main__\":\n    HOST, PORT = \"localhost\", 9999\n\n    # Init the TCP server object, bind it to the localhost on 9999 port\n    tcp_server = socketserver.TCPServer((HOST, PORT), Handler_TCPServer)\n\n    # Activate the TCP server.\n    # To abort the TCP server, press Ctrl-C.\n    tcp_server.serve_forever()\n<\/pre>\n\n\n\n<p>In the next example code, you&#8217;ll see the Python TCP client module code to communicate with the TCP server.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-python-tcp-client-py\">Python-TCP-Client.py<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">import socket\n\nhost_ip, server_port = \"127.0.0.1\", 9999\ndata = \" Hello how are you?\\n\"\n\n# Initialize a TCP client socket using SOCK_STREAM\ntcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ntry:\n    # Establish connection to TCP server and exchange data\n    tcp_client.connect((host_ip, server_port))\n    tcp_client.sendall(data.encode())\n\n    # Read data from the TCP server and close the connection\n    received = tcp_client.recv(1024)\nfinally:\n    tcp_client.close()\n\nprint (\"Bytes Sent:     {}\".format(data))\nprint (\"Bytes Received: {}\".format(received.decode()))\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-execution-of-python-tcp-server-and-client-modules\">Execution of Python TCP Server and Client modules<\/h3>\n\n\n\n<p>You can run both the server and client in separate Python instances. We recommend that you use Python version 3 for executing the above modules.<\/p>\n\n\n\n<p>Next, you would first run the server module followed by the client. See below the output of both the client and the server.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n \n RESTART: C:\\Users\\Techbeamers\\AppData\\Local\\Programs\\Python\\Python35\\Python-TCP-Server.py \n\n127.0.0.1 sent:\nb'Hello how are you?'<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n\n RESTART: C:\\Users\\Techbeamers\\AppData\\Local\\Programs\\Python\\Python35\\Python-TCP-Client.py \nBytes Sent:      Hello how are you?\n\nBytes Received: ACK from TCP Server\n<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-final-word-create-a-tcp-server-client-in-python\">Final Word &#8211;&nbsp;Create a TCP Server-Client in Python<\/h2>\n\n\n\n<p>We always share what we think is useful for our readers like this blog post and other ones in the series of Python socket programming. We hope this Python tutorial and the TCP server example would have served your purpose to visit our blog.<\/p>\n\n\n\n<p>So, do give us your support and share this post using the sharing icons given below.<\/p>\n\n\n\n<p>Lastly, we believe that Python is powerful and it works to the expectations.<\/p>\n\n\n\n<p><strong>Best,<\/strong><\/p>\n\n\n\n<p><strong>TechBeamers<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python is one of the most popular object-oriented scripting languages with a programmer-friendly syntax and a vast developer community.&nbsp;This tutorial explains the concept of networking programming with the help of Python classes. Here, we&#8217;ll showcase&nbsp;how to write a TCP server and client in Python and implement them using classes. In&nbsp;our previous Python socket programming tutorials, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":4958,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","jetpack_post_was_ever_published":false},"categories":[92],"tags":[],"class_list":{"0":"post-2048","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python-programming-tutorials"},"jetpack_featured_media_url":"https:\/\/techbeamers.com\/wp-content\/uploads\/2016\/03\/Implement-a-TCP-Server-and-Client-Using-Socket-Class-in-Python.png","_links":{"self":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/2048","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/comments?post=2048"}],"version-history":[{"count":1,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/2048\/revisions"}],"predecessor-version":[{"id":23502,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/2048\/revisions\/23502"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media\/4958"}],"wp:attachment":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media?parent=2048"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/categories?post=2048"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/tags?post=2048"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}