{"id":1562,"date":"2023-10-17T21:25:16","date_gmt":"2023-10-17T15:55:16","guid":{"rendered":"https:\/\/geekpython.in\/?p=1562"},"modified":"2024-03-01T17:05:14","modified_gmt":"2024-03-01T11:35:14","slug":"build-websocket-server-and-client-using-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/build-websocket-server-and-client-using-python","title":{"rendered":"Build WebSocket Server and Client Using Python"},"content":{"rendered":"\n<p>You must have seen real-time applications where data is changed frequently or updated in real-time, this happens because that application is using a WebSocket to achieve this functionality.<\/p>\n\n\n\n<p>By the end of this article, you&#8217;ll able to learn:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>What is WebSocket?<\/li>\n\n\n\n<li>How to create a WebSocket server and client using Python?<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What is WebSocket?<\/h2>\n\n\n\n<p>A <strong>WebSocket<\/strong> allows two-way communication (bidirectional) between two entities over a single TCP connection. This means a WebSocket client and server can interact with each other multiple times in a single connection.<\/p>\n\n\n\n<p>A Websocket connection is a fully-duplex connection protocol which means the data can be sent and received simultaneously in both directions, keeping the connection alive until either server or client decides to stop the connection.<\/p>\n\n\n\n<p>It is used in real-time applications to exchange low-latency data in both directions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to Create a WebSocket using Python<\/h2>\n\n\n\n<p>In this section, you will create a WebSocket server and client using Python. You will use Python&#8217;s <code>websockets<\/code> library to create a server and a client.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Install Dependency<\/h3>\n\n\n\n<p>Open your terminal window and run the following command:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">pip install websockets<\/pre><\/div>\n\n\n\n<p>Using the <code>websockets<\/code> library, you can create a websocket server and client in Python super easily.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Create a WebSocket Server<\/h3>\n\n\n\n<p>In this section, you&#8217;ll create a WebSocket server that will retrieve the values from the client and based on those values sends the appropriate response to the client.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" title=\"main.py\">import websockets\nimport asyncio\n\n# Creating WebSocket server\nasync def ws_server(websocket):\n    print(\"WebSocket: Server Started.\")\n\n    try:\n        while True:\n            # Receiving values from client\n            name = await websocket.recv()\n            age = await websocket.recv()\n\n            # Prompt message when any of the field is missing\n            if name == \"\" or age == \"\":\n                print(\"Error Receiving Value from Client.\")\n                break\n\n            # Printing details received by client\n            print(\"Details Received from Client:\")\n            print(f\"Name: {name}\")\n            print(f\"Age: {age}\")\n\n            # Sending a response back to the client\n            if int(age) &lt; 18:\n                await websocket.send(f\"Sorry! {name}, You can't join the club.\")\n            else:\n                await websocket.send(f\"Welcome aboard, {name}.\")\n\n    except websockets.ConnectionClosedError:\n        print(\"Internal Server Error.\")\n\n\nasync def main():\n    async with websockets.serve(ws_server, \"localhost\", 7890):\n        await asyncio.Future()  # run forever\n\nif __name__ == \"__main__\":\n    asyncio.run(main())<\/pre><\/div>\n\n\n\n<p>The above code imports the <code>websockets<\/code> library for creating a WebSocket server and communicating with it and the <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python\"><code>asyncio<\/code><\/a> library for making use of asynchronous tasks.<\/p>\n\n\n\n<p>The code then defines an asynchronous function called <code>ws_server()<\/code> that takes WebSocket connection (<code>websocket<\/code>) as its parameter.<\/p>\n\n\n\n<p>Inside the function, a <code>try<\/code> block is used that handles the incoming messages from the client. Within the <code>try<\/code> block, a <code>while<\/code> loop is created which means the code will run continuously.<\/p>\n\n\n\n<p>Within the loop, the code receives two values from the client using the <code>websocket.recv()<\/code> and stores them within the <code>name<\/code> and <code>age<\/code> variables respectively. The code checks if any of the value is missing, if it is then it prompts a message and breaks the loops otherwise it proceeds and prints the values received from the client.<\/p>\n\n\n\n<p>The code then sends the appropriate response back to the client based on the values it gets.<\/p>\n\n\n\n<p>In the <code>except<\/code> block, the code handles any <code>websockets.ConnectionClosedError<\/code> exceptions that indicate an error occurred during the connection.<\/p>\n\n\n\n<p>The code then defines another asynchronous function called <code>main()<\/code> that starts a WebSocket server. The WebSocket server is created using <code>websockets.serve()<\/code> method which listens on <code>localhost<\/code> and port <code>7890<\/code>.<\/p>\n\n\n\n<p>The server will run forever due to <code>asyncio.Future()<\/code>. This will keep the server alive and run continuously to listen to incoming messages.<\/p>\n\n\n\n<p>In the end, the <code>main()<\/code> function is run using the <code>asyncio.run(main())<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Create a WebSocket Client<\/h3>\n\n\n\n<p>In this section, you&#8217;ll create a client that takes the input from the user and displays the response sent by the WebSocket server.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" title=\"client.py\">import websockets\nimport asyncio\n\n# The main function that will handle connection and communication\n# with the server\nasync def ws_client():\n    print(\"WebSocket: Client Connected.\")\n    url = \"ws:\/\/127.0.0.1:7890\"\n    # Connect to the server\n    async with websockets.connect(url) as ws:\n        name = input(\"Your Name (type 'exit' to quit): \")\n\n        if name == 'exit':\n            exit()\n\n        age = input(\"Your Age: \")\n        # Send values to the server\n        await ws.send(f\"{name}\")\n        await ws.send(f\"{age}\")\n\n        # Stay alive forever, listen to incoming msgs\n        while True:\n            msg = await ws.recv()\n            print(msg)\n\n# Start the connection\nasyncio.run(ws_client())<\/pre><\/div>\n\n\n\n<p>The above code defines an asynchronous function called <code>ws_client()<\/code>. Inside the function, the WebSocket client is connected to the WebSocket server using the <code>websockets.connect()<\/code> method passed with the URL (<code>ws:\/\/127.0.0.1:789<\/code>) of the server created in the previous section.<\/p>\n\n\n\n<p>The user is prompted to enter the name and if they type <strong>&#8220;exit&#8221;<\/strong>, the code quits the process. Then the user is asked to enter their age and both values (<code>name<\/code> and <code>age<\/code>) are sent to the WebSocket server using the <code>ws.send()<\/code> method.<\/p>\n\n\n\n<p>After that, the code enters the infinite loop to continuously listen to the incoming messages from the server using the <code>ws.recv()<\/code> method. The message is then printed on the console.<\/p>\n\n\n\n<p>Finally, the <code>ws_client()<\/code> function is run using <code>asyncio.run(ws_client())<\/code>. This will start the WebSocket client to accept the information from the user and display the response sent by the server.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Running the WebSocket Server and Client<\/h2>\n\n\n\n<p>You need to put the server and client code in two separate Python files. First, you need to run the WebSocket server script to start the server.<\/p>\n\n\n\n<p>Open a terminal window, navigate to the project directory, and run the script file, in this case, the script is stored in the <code>main.py<\/code> Python file.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">python main.py<\/pre><\/div>\n\n\n\n<p>Now open another terminal window and run the WebSocket client script, in this case, the script is stored in the <code>client.py<\/code> file.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">python client.py<\/pre><\/div>\n\n\n\n<p>This will start the WebSocket client connected to the server. You will see the prompts asking for your <strong>name<\/strong> and <strong>age<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"618\" height=\"240\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/10\/image-3.png\" alt=\"WebSocket client\" class=\"wp-image-1565\" srcset=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/10\/image-3.png 618w, https:\/\/geekpython.in\/wp-content\/uploads\/2023\/10\/image-3-300x117.png 300w\" sizes=\"auto, (max-width: 618px) 100vw, 618px\" \/><\/figure><\/div>\n\n\n<p>Here, <code>\"Sachin\"<\/code> and <code>\"22\"<\/code> are sent to the server, and in return, the server responds with the <code>\"Welcome aboard, Sachin\"<\/code> message on the console.<\/p>\n\n\n\n<p>The information entered by the user will be displayed on the WebSocket server console. You can see this in the image below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"618\" height=\"240\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/10\/image-4.png\" alt=\"WebSocket server\" class=\"wp-image-1566\" srcset=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/10\/image-4.png 618w, https:\/\/geekpython.in\/wp-content\/uploads\/2023\/10\/image-4-300x117.png 300w\" sizes=\"auto, (max-width: 618px) 100vw, 618px\" \/><\/figure><\/div>\n\n\n<p>You can also run the client using the websockets interactive shell using the following command.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">python -m websockets ws:\/\/localhost:7890<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, you learned to create a WebSocket server and client using the websockets library in Python. This technology is used in applications in which data changes in real-time.<\/p>\n\n\n\n<p>Resource: <a href=\"https:\/\/websockets.readthedocs.io\/en\/stable\/howto\/quickstart.html\" target=\"_blank\" rel=\"noopener\">https:\/\/websockets.readthedocs.io\/en\/stable\/howto\/quickstart.html<\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/threading-module-to-create-threads-in-python\">Create multi-threaded Python programs using a threading module<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/how-to-use-sklearn-standardscaler\">What is the StandardScaler function in Machine Learning<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/render-images-from-flask\">Upload and display images on the frontend using Flask<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/advanced-python-coroutines-best-practices-for-efficient-asynchronous-programming\">What is Python coroutines and how to use it to execute tasks asynchronously<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python\">How to use async\/await in Python using the asyncio module<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/database-in-appwrite-using-python\">How to create a database on Appwrite cloud using only Python<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>You must have seen real-time applications where data is changed frequently or updated in real-time, this happens because that application is using a WebSocket to achieve this functionality. By the end of this article, you&#8217;ll able to learn: What is WebSocket? A WebSocket allows two-way communication (bidirectional) between two entities over a single TCP connection. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1564,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[2],"tags":[12,74],"class_list":["post-1562","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python","tag-websocket","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1562","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1562"}],"version-history":[{"count":4,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1562\/revisions"}],"predecessor-version":[{"id":1569,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1562\/revisions\/1569"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1564"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1562"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1562"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1562"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}