{"id":339,"date":"2023-08-02T15:36:18","date_gmt":"2023-08-02T15:36:18","guid":{"rendered":"http:\/\/python.garden\/?p=339"},"modified":"2023-08-07T16:17:31","modified_gmt":"2023-08-07T16:17:31","slug":"beginners-guide-to-python-socket-programming","status":"publish","type":"post","link":"https:\/\/python.garden\/index.php\/2023\/08\/02\/beginners-guide-to-python-socket-programming\/","title":{"rendered":"Beginners Guide to Python Socket Programming"},"content":{"rendered":"\n<p>The <code>socket<\/code> module in Python provides a way to communicate between two computers using the TCP\/IP protocol. Here we will write a simple chat application that consists of a server and a client.<\/p>\n\n\n\n<p><strong>What is a Socket?<\/strong><\/p>\n\n\n\n<p>A socket is one endpoint of a two-way communication link between two programs running on the network. Sockets are used to create a connection between a client program and a server program. The client program is run on one machine and sends a request to a certain IP address and port number; the server program is run on the other machine and waits for requests on that specified port.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Python Socket Programming Steps<\/h3>\n\n\n\n<p><strong>Step 1: Import Socket Module<\/strong><\/p>\n\n\n\n<p>The first step in Python socket programming is to import the socket module.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">import socket<\/pre><\/div>\n\n\n\n<p><strong>Step 2: Create a Socket<\/strong><\/p>\n\n\n\n<p>Next, you need to create a socket. You can do this using the <code>socket.socket()<\/code> method.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<\/pre><\/div>\n\n\n\n<p>Here, <code>socket.AF_INET<\/code> refers to the address family ipv4 and <code>socket.SOCK_STREAM<\/code> means that it is a TCP socket.<\/p>\n\n\n\n<p><strong>Step 3: Bind the Socket<\/strong><\/p>\n\n\n\n<p>The next step is to bind the socket to a specific address and port. You can do this using the <code>socket.bind()<\/code> method.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">s.bind((host, port))<\/pre><\/div>\n\n\n\n<p><strong>Step 4: Listen for Connections<\/strong><\/p>\n\n\n\n<p>Once you have bound your socket, you can start listening for connections. You can do this using the <code>socket.listen()<\/code> method.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">s.listen()<\/pre><\/div>\n\n\n\n<p><strong>Step 5: Accept Connections<\/strong><\/p>\n\n\n\n<p>After listening for connections, you can accept them using the <code>socket.accept()<\/code> method. This method will return a new socket object and the address of the client.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">client_socket, addr = s.accept()<\/pre><\/div>\n\n\n\n<p><strong>Step 6: Send and Receive Data<\/strong><\/p>\n\n\n\n<p>Once you have a connection, you can send and receive data using the <code>send()<\/code> and <code>recv()<\/code> methods.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">data = client_socket.recv(1024)\nclient_socket.send(data)<\/pre><\/div>\n\n\n\n<p><strong>Step 7: Close the Socket<\/strong><\/p>\n\n\n\n<p>When you are done with the connection, you should close the socket to free up resources.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">s.close()<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Simple Chat Server &amp; Client Example<\/h3>\n\n\n\n<p><strong>Server Code:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">import socket\n\n# Create a socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Define the host and the port\nhost = 'localhost'\nport = 12345\n\n# Bind the socket\ns.bind((host, port))\n\n# Start listening for connections\ns.listen()\n\nprint(f'Server started on {host}:{port}, waiting for connections...')\n\nwhile True:\n    # Accept a connection\n    client_socket, addr = s.accept()\n\n    print(f'Got a connection from {addr}')\n\n    # Receive data\n    data = client_socket.recv(1024).decode('utf-8')\n    print(f'Received message: {data} from: {addr}')\n\n    # Send data\n    response = 'Server response: ' + data\n    client_socket.send(response.encode('utf-8'))\n\n    # Close the connection\n    client_socket.close()<\/pre><\/div>\n\n\n\n<p><strong>Client Code:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">import socket\n\n# Create a socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Define the host and the port\nhost = 'localhost'\nport = 12345\n\n# Connect to the server\ns.connect((host, port))\n\n# Send some data\nmessage = 'Hello, Server!'\ns.send(message.encode('utf-8'))\n\n# Receive data\ndata = s.recv(1024).decode('utf-8')\nprint(f'Received from server: {data}')\n\n# Close the connection\ns.close()<\/pre><\/div>\n\n\n\n<p>Note: Remember to run the server script first before running the client script. Also, this simple chat application sends and receives a single message; to have a continuous chat, you can wrap the sending and receiving of data in a loop. But remember to set a condition to break the loop to prevent an infinite loop.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The socket module in Python provides a way to communicate between two computers using the TCP\/IP protocol. Here we will write a simple chat application that consists of a server&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[214,213],"tags":[],"class_list":["post-339","post","type-post","status-publish","format-standard","hentry","category-beginners-guide","category-python"],"featured_image_src":null,"author_info":{"display_name":"shababdoo","author_link":"https:\/\/python.garden\/index.php\/author\/shababdoo\/"},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/posts\/339","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/comments?post=339"}],"version-history":[{"count":0,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/posts\/339\/revisions"}],"wp:attachment":[{"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/media?parent=339"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/categories?post=339"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/tags?post=339"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}