
    
        
        
        
                
        
        
        
                
        
        
        
                
        
        
        
                
        
        
        
            
{"version":"https:\/\/jsonfeed.org\/version\/1","title":"mathspp.com feed","home_page_url":"https:\/\/mathspp.com\/blog\/tags\/networking","feed_url":"https:\/\/mathspp.com\/blog\/tags\/networking.json","description":"Stay up-to-date with the articles on mathematics and programming that get published to mathspp.com.","author":{"name":"Rodrigo Gir\u00e3o Serr\u00e3o"},"items":[{"title":"Connecting Python and Dyalog APL with sockets","date_published":"2023-01-21T00:00:00+01:00","id":"https:\/\/mathspp.com\/blog\/connecting-python-and-dyalog-apl-with-sockets","url":"https:\/\/mathspp.com\/blog\/connecting-python-and-dyalog-apl-with-sockets","content_html":"<p>This article shows how to communicate between Python and Dyalog APL through the use of sockets. We will use the module <code>socket<\/code> from Python and the Conga workspace from Dyalog.<\/p>\n\n<p><img alt=\"\" src=\"\/images\/c\/7\/9\/3\/2\/c793259a18fd94998098f3c57fd8b3b1abf2b7ad-thumbnail.webp\"><\/p>\n<h2 id=\"introduction\">Introduction<a href=\"#introduction\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Programs communicate with each other all the time.\nFor example, your browser communicated with my server to retrieve this article.\nSometimes, you may want your programs to communicate with others, and when that time comes, you may want to use sockets<sup id=\"fnref1:1\"><a href=\"#fn:1\" class=\"footnote-ref\">1<\/a><\/sup>.<\/p>\n<p>This article will show how to communicate between Python and <a href=\"https:\/\/dyalog.com\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">Dyalog APL<\/a> using sockets:<\/p>\n<ul><li>we will use the module <code>sockets<\/code> on the Python side; and<\/li>\n<li>we will use Conga on the Dyalog APL side.<\/li>\n<\/ul><p>Both <code>sockets<\/code> for Python and Conga for Dyalog APL come with their respective systems by default, so that should make things easier for us.<\/p>\n<h2 id=\"how-to-create-a-socket-server-in-python\">How to create a socket server in Python<a href=\"#how-to-create-a-socket-server-in-python\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Thanks to some investigation I did some months ago and <a href=\"\/blog\/til\/sockets\">an article I wrote about <code>sockets<\/code><\/a>, we can see that it doesn't take much code to create a socket server in Python.<\/p>\n<p>In fact, the four lines of code that follow are enough to create a socket server in Python that will listen on port 7342 on the local host:<\/p>\n<pre><code class=\"language-py\">import socket\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind((\"localhost\", 7342))\nserver.listen()<\/code><\/pre>\n<p>If you are following along, what I suggest is that you run this code in your REPL, so that the Dyalog APL socket you create in the next step connects to your server and you see what is going on.<\/p>\n<p>Go ahead, paste those four lines of code in your REPL, and then add this fifth one to wait for a socket to connect:<\/p>\n<pre><code class=\"language-py\">client, address = server.accept()<\/code><\/pre>\n<p>If all went well, running that line of code should make your interpreter hang, which is normal because you are waiting for a socket to connect to your server.<\/p>\n<p>Let's see how to connect from the APL side<\/p>\n<h2 id=\"how-to-create-a-client-socket-in-dyalog-apl\">How to create a client socket in Dyalog APL<a href=\"#how-to-create-a-client-socket-in-dyalog-apl\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>To work with sockets in Dyalog APL we need to load the Conga workspace, or we can just copy the namespace <code>DRC<\/code> in:<\/p>\n<pre><code class=\"language-apl\">      )copy conga DRC<\/code><\/pre>\n<p>Next up, we initialise the namespace:<\/p>\n<pre><code class=\"language-apl\">      DRC.Init ''\n&#9484;&#9472;&#9516;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;\n&#9474;0&#9474;Conga loaded from: conga34_64&#9474;\n&#9492;&#9472;&#9524;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9496;<\/code><\/pre>\n<p>The exact numbers you get in the <code>conga34_64<\/code> portion of the output will differ from version to version (and possibly from OS to OS).<\/p>\n<p>Finally, we use the function <code>DRC.Clt<\/code> to create a client socket.\nWe will pass four arguments to <code>DRC.Clt<\/code>:<\/p>\n<ul><li>the name of the socket we are going to create (any character vector will do);<\/li>\n<li>the address or name of the host (<code>'localhost'<\/code> in our example);<\/li>\n<li>the port to which to connect to (<code>7342<\/code> in our example); and<\/li>\n<li>the type of the socket (<code>'Text'<\/code> in our example):<\/li>\n<\/ul><pre><code class=\"language-apl\">      DRC.Clt 'my socket' 'localhost' 7342 'Text'\n&#9484;&#9472;&#9516;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;\n&#9474;0&#9474;my socket&#9474;\n&#9492;&#9472;&#9524;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9496;<\/code><\/pre>\n<p>If the first element of the result vector is a <code>0<\/code>, that means everything worked out and you managed to create your socket.\nOtherwise, that integer will have an error code...<\/p>","summary":"This article shows how to communicate between Python and Dyalog APL through the use of sockets. We will use the module `socket` from Python and the Conga workspace from Dyalog.","date_modified":"2025-07-23T16:49:02+02:00","tags":["apl","networking","python"],"image":"\/user\/pages\/02.blog\/connecting-python-and-dyalog-apl-with-sockets\/thumbnail.webp"},{"title":"Chatroom server tutorial","date_published":"2022-01-19T00:00:00+01:00","id":"https:\/\/mathspp.com\/blog\/chatroom-server-tutorial","url":"https:\/\/mathspp.com\/blog\/chatroom-server-tutorial","content_html":"<p>Create a simple chatroom server in Python by following along this tutorial series.<\/p>\n\n<figure class=\"image-caption\"><img title=\"Photo by Jason Leung on Unsplash.\" alt=\"\" src=\"\/images\/a\/2\/b\/4\/8\/a2b48c89071c1eb946b2bf828997987eeb118443-thumbnail.png\"><figcaption class=\"\">Photo by Jason Leung on Unsplash.<\/figcaption><\/figure><h2 id=\"introduction\">Introduction<a href=\"#introduction\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>I started learning about sockets and network programming very recently,\nand my knowledge is still very limited.\nBecause of that, I figured the best thing I could do was build <em>something<\/em> that made use of my new knowledge.<\/p>\n<p>I decided to build a simple chatroom server in Python,\nand I will also write accompanying blog articles that will allow you to tag along\nand build a simple chatroom server in Python with me.<\/p>\n<p>The articles in this series are not intended to represent the best practices in the field,\nnor do I claim that I am doing things in the best way possible.\nI'm just exploring, trying to get things to work, and you are welcome to join me!<\/p>\n<p>If you have suggestions, leave a comment below or <a href=\"\/about\">reach out to me directly<\/a>!<\/p>\n<div class=\"notices blue\">\n<p>The code lives in <a href=\"https:\/\/github.com\/mathspp\/sockchat\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">this GitHub repository<\/a>.<\/p>\n<\/div>\n<h3 id=\"pre-requisites\">Pre-requisites<a href=\"#pre-requisites\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h3>\n<p>The pre-requisites for following along this tutorial are a basic understanding of sockets,\nhow to use them in Python, and an intermediate knowledge of Python.<\/p>\n<p>As far as the basic understanding of sockets goes,\nyou can get on my level by reading <a href=\"\/blog\/sockets-for-dummies\">this &ldquo;Sockets for Dummies&rdquo; article<\/a>.\nI wrote that article <em>while<\/em> I was learning about sockets,\nand in that article I share experiments that you can try that will help you understand sockets.<\/p>\n<p>Throughout the series, I will be explaining new concepts and tools regarding socket programming.<\/p>\n<p>If you find yourself struggling with something regarding the Python langauge itself,\nyou can always take a look at my <a href=\"\/blog\/pydonts\">Pydon'ts series<\/a>.<\/p>\n<h3 id=\"roadmap\">Roadmap<a href=\"#roadmap\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h3>\n<p>When I am preparing to build something, I always think of a high-level roadmap to follow.\nNot only that, but I tend to do the plan in a very specific way:\nI like to build my projects incrementally.\nAt every step of the way, I like to have something that I can play around with.\nOn the other hand, I don't like to have to write <em>all<\/em> the code first,\nand only then see the end result of what I created.<\/p>\n<p>Before I can create the roadmap, first I have to figure out (more or less)\nwhat the components of the project are.\nFor this chatroom server, we need two things:<\/p>\n<ul><li>a piece of code that manages the chatroom, all the messages people are sending, etc; and<\/li>\n<li>a piece of code that allows users to connect to the chatroom, send messages, and read messages.<\/li>\n<\/ul><p>Because I want to use sockets for this purpose, I thought of this diagram:<\/p>\n<figure class=\"image-caption\"><img title=\"A client sends a message to the server, which then broadcasts it to the other clients.\" alt=\"A diagram that summarises the main architecture of the chatroom server written in Python, where a client socket sends messages to the server, which then broadcasts them to the other client sockets.\" src=\"\/user\/pages\/02.blog\/chatroom-server-tutorial\/_server_client.webp\"><figcaption class=\"\">A client sends a message to the server, which then broadcasts it to the other clients.<\/figcaption><\/figure><p>This is the basic way in which I imagine the chatroom server will function:\nwhenever a user types a message, its client socket will send the message to the server.\nThe server is then responsible for taking that message and broadcasting it to all\nother users\/client sockets that are connected....<\/p>","summary":"Create a simple chatroom server in Python by following along this tutorial series.","date_modified":"2025-07-23T16:49:02+02:00","tags":["networking","programming","python"],"image":"\/user\/pages\/02.blog\/chatroom-server-tutorial\/thumbnail.png"},{"title":"TIL #022 \u2013 Python module selectors","date_published":"2022-01-14T00:00:00+01:00","id":"https:\/\/mathspp.com\/blog\/til\/022","url":"https:\/\/mathspp.com\/blog\/til\/022","content_html":"<p>Today I learned about the Python module <code>selectors<\/code> to manage multiple socket connections.<\/p>\n\n<p><img alt=\"The Python import statement that allows us to use the Python module `selectors`.\" src=\"\/images\/4\/5\/b\/f\/a\/45bfabf50df6570344fa50d7758ce0d87304f72f-thumbnail.webp\"><\/p>\n<h2 id=\"selectors\"><code>selectors<\/code><a href=\"#selectors\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Following up on some of <a href=\"\/blog\/sockets-for-dummies\">my recent efforts to learn socket programming<\/a>,\nI learned about the Python module <code>selectors<\/code>.\nThis module is very helpful when you need to manage multiple socket connections\nand you don't want to spawn a new thread to handle each socket separately.<\/p>\n<p>The relevance of this module arises from the fact that, if nothing else is done,\ncalling the method <code>recv<\/code> method of a client socket &ndash; or the method <code>accept<\/code> of a server socket &ndash; blocks.\nFor example, for the server socket, this means that the call to <code>accept<\/code> won't return while no connection is accepted.<\/p>\n<p>Try pasting this code in a script and run it:<\/p>\n<pre><code class=\"language-py\">## server.py\nimport socket\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind((\"localhost\", 7342))\nserver.listen()\nprint(\"About to accept:\")\nserver.accept()\nprint(\"Call to `accept` returned.\")<\/code><\/pre>\n<p>If you run this with <code>python server.py<\/code>, the message <code>\"About to accept:\"<\/code> gets printed,\nbut not the message <code>\"Call to `accept` returned.\"<\/code>.\nWhy?\nBecause there is no connection to be accept, and so the call to <code>accept<\/code> blocks,\nwaiting for a connection.<\/p>\n<p>Thus, we can't <em>just<\/em> call the method <code>recv<\/code> on the different clients we have,\nbecause if one doesn't have anything for us, we will block!\nA common way to deal with this is by spawning a thread for each client,\nand do the blocking calls in those separate threads.<\/p>\n<p>Another way to deal with this is with the module <code>selectors<\/code>.<\/p>\n<p>Here is my intuitive understanding of what the module <code>selectors<\/code> does:\nyou take all the sockets that you care about, and you put them in a big bag of sockets.\nThen, the module <code>selectors<\/code> can take a look at the bag and give you the sockets\nthat are ready to be read from\/written to; you just have to ask.<\/p>\n<p>For example, here is how you can use the module <code>selectors<\/code> to only\ntry accepting a connection to the server socket when one is ready:<\/p>\n<pre><code class=\"language-py\">## server.py\n\nimport selectors\nimport socket\n\n## Set up the server\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind((\"localhost\", 7342))\nserver.listen()\n\n## Set up the selectors \"bag of sockets\"\nselector = selectors.DefaultSelector()\nselector.register(server, selectors.EVENT_READ)\n\nwhile True:\n    events = selector.select()\n    for key, _ in events:\n        sock = key.fileobj\n        print(\"About to accept.\")\n        client, _ = sock.accept()\n        print(\"Accepted.\")<\/code><\/pre>\n<p>If you paste this code in a file <code>server.py<\/code> and run it with <code>python server.py<\/code>,\nyou will see that it hangs once more, but it didn't hang in the call to the method <code>accept<\/code>.<\/p>\n<p>If you open a new REPL, create a client socket, and connect to the server,\nyou will see that the two messages <code>\"About to accept.\"<\/code> and <code>\"Accepted.\"<\/code> get printed back to back.<\/p>\n<p>The GIF below shows that the two messages get printed pretty much at the same time,\nproving that the code is not hanging because of the call to <code>accept<\/code>:<\/p>\n<p><img alt=\"GIF that proves that the Python module `selectors` allows multiplexing between sockets.\" src=\"\/user\/pages\/02.blog\/04.til\/022.python-module-selectors\/_selectors_accept_doesnt_block.gif?decoding=auto&amp;fetchpriority=auto\"><\/p>\n<h2 id=\"registering-with-a-callback\">Registering with a callback<a href=\"#registering-with-a-callback\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>There are many, <em>many<\/em> details I didn't cover about the module...<\/p>","summary":"Today I learned about the Python module `selectors` to manage multiple socket connections.","date_modified":"2025-07-23T16:49:02+02:00","tags":["networking","programming","python"],"image":"\/user\/pages\/02.blog\/04.til\/022.python-module-selectors\/thumbnail.webp"},{"title":"Sockets for dummies","date_published":"2022-01-12T00:00:00+01:00","id":"https:\/\/mathspp.com\/blog\/sockets-for-dummies","url":"https:\/\/mathspp.com\/blog\/sockets-for-dummies","content_html":"<p>Dive into the world of socket programming with this Python tutorial that assumes 0 prior experience.<\/p>\n\n<script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script><figure class=\"image-caption\"><img title=\"Phone and laptop communicating through sockets.\" alt=\"A picture of a phone and a laptop, showing that the phone managed to use Python to send data into the laptop through sockets, one of the experiments done in this Python tutorial that serves as an introduction to sockets and networking.\" src=\"\/user\/pages\/02.blog\/sockets-for-dummies\/thumbnail.png\"><figcaption class=\"\">Phone and laptop communicating through sockets.<\/figcaption><\/figure><h2 id=\"motivation-and-starting-point\">Motivation and starting point<a href=\"#motivation-and-starting-point\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>I need to learn about socket programming for work.\nI was tasked with maintaining a project (<a href=\"https:\/\/github.com\/Dyalog\/pynapl\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">Py'n'APL<\/a>) that revolves around sockets,\nso I figured I can't really maintain <a href=\"https:\/\/github.com\/Dyalog\/pynapl\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">Py'n'APL<\/a> without knowing what I'm messing with.<\/p>\n<p>I have no networking knowledge whatsoever,\nand I'm starting this learning experience with the impression that sockets are like tunnels\/roads\nthat allow different programs to communicate.\nThis is my (limited) intuitive understanding of sockets,\nwhich we'll find out together whether it is a decent intuition or not.<\/p>\n<p>My generic game plan is to read enough about sockets so that:<\/p>\n<ul><li>I can explain what sockets are to others;<\/li>\n<li>I can manipulate sockets in my Python programs; and<\/li>\n<li>I can make use of sockets in my Python programs to have them communicate with each other.<\/li>\n<\/ul><h3 id=\"learning-in-public\">Learning in public<a href=\"#learning-in-public\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h3>\n<p>At the same time I learn about socket programming <em>and<\/em> write this article,\nI will be sharing my almost-real-time findings, ideas, and experiments, on Twitter.\nIf you are reading this, it means I already did that, but here is the Twitter thread\nthat I wrote while learning about socket programming in public:<\/p>\n<blockquote class=\"twitter-tweet\">\n<p lang=\"en\" dir=\"ltr\">Today, I'm spending the day learning in public about socket programming (in Python &#128013;).<br><br>My starting point is this:<br><br>&ldquo;I think sockets are like tunnels\/roads that allow different programs to talk to each other directly.&rdquo;<br><br>This &#129525; will evolve as I learn and experiment &#128071;<\/p>&mdash; Rodrigo &#128013;&#128221; (@mathsppblog) <a href=\"https:\/\/twitter.com\/mathsppblog\/status\/1478321570892320768?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">January 4, 2022<\/a>\n<\/blockquote>\n<h2 id=\"client-and-server-sockets\">Client and server sockets<a href=\"#client-and-server-sockets\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>The first step in my journey to understanding socket programming is going through the\n&ldquo;Socket Programming HOWTO&rdquo; available in the Python docs, and that you can read <a href=\"https:\/\/docs.python.org\/3\/howto\/sockets.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">here<\/a>.<\/p>\n<p>As we read through the <a href=\"https:\/\/docs.python.org\/3\/howto\/sockets.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">HOWTO<\/a>, we learn about &ldquo;IPC&rdquo;:<\/p>\n<div class=\"notices blue\">\n<p>IPC stands for Inter-Process Communication,\nwhich validates the idea that sockets are useful for programs to communicate with each other.<\/p>\n<\/div>\n<p>It also tells us about the distinction between a &ldquo;client socket&rdquo; and a &ldquo;server socket&rdquo;.<\/p>\n<p>A &ldquo;server socket&rdquo; is described as a switchboard operator.\nMy understanding of that is that the server (socket) is responsible for accepting\ncommunications &ldquo;from the outside world&rdquo;, and handling those.<\/p>\n<p>The &ldquo;client socket&rdquo; seems to be the socket that wants to connect to a given server,\nin order to communicate with it.<\/p>\n<p>The example given in that <a href=\"https:\/\/docs.python.org\/3\/howto\/sockets.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">HOWTO<\/a> is that of a web browser:\nyour web browser acts as (or uses?) a client socket to connect to a website.\nFor example, in order to read this article, your browser had to use a client socket\nto access my domain.\nOn my end, my web server has a socket server that accepts these connections\nfrom people like you, and then returns the web pages.<\/p>\n<p>The <a href=\"https:\/\/docs.python.org\/3\/howto\/sockets.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">HOWTO<\/a> actually says that the web server uses both server sockets and client sockets...\nSo, perhaps the server socket is in charge of accepting the connections,\nbut then it also uses a client socket...<\/p>","summary":"Dive into the world of socket programming with this Python tutorial that assumes 0 prior experience.","date_modified":"2025-07-23T16:49:02+02:00","tags":["networking","programming","python"],"image":"\/user\/pages\/02.blog\/sockets-for-dummies\/thumbnail.png"},{"title":"TIL #019 \u2013 sockets","date_published":"2022-01-04T00:00:00+01:00","id":"https:\/\/mathspp.com\/blog\/til\/019","url":"https:\/\/mathspp.com\/blog\/til\/019","content_html":"<p>Today I learned the basics of socket programming (in Python).<\/p>\n\n<script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script><figure class=\"image-caption\"><img title=\"Photo by Tom Dahm on Unsplash\" alt=\"A tunnel, alluding to my intuitive understanding of what a socket is.\" src=\"\/images\/d\/7\/6\/e\/a\/d76ea6d958031db123043e5faebd30a61baf29da-thumbnail.png\"><figcaption class=\"\">Photo by Tom Dahm on Unsplash<\/figcaption><\/figure><h2 id=\"sockets\">Sockets<a href=\"#sockets\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>When the day started, I had <em>very little knowledge<\/em> about sockets.\nMy intuitive understanding was that they were like tunnels that allowed\ndifferent programs to communicate between themselves.<\/p>\n<p>Now that the day is ending, I still don't know <em>much<\/em> about sockets,\nbut I did spend the day reading about them and experimenting with them.<\/p>\n<p>I have been documenting the process publicly:<\/p>\n<blockquote class=\"twitter-tweet\">\n<p lang=\"en\" dir=\"ltr\">Today, I'm spending the day learning in public about socket programming (in Python &#128013;).<br><br>My starting point is this:<br><br>&ldquo;I think sockets are like tunnels\/roads that allow different programs to talk to each other directly.&rdquo;<br><br>This &#129525; will evolve as I learn and experiment &#128071;<\/p>&mdash; Rodrigo &#128013;&#128221; (@mathsppblog) <a href=\"https:\/\/twitter.com\/mathsppblog\/status\/1478321570892320768?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">January 4, 2022<\/a>\n<\/blockquote>\n<p>This helps me make sure I learn as much as possible.\nIt also helps, because others chime in with interesting suggestions quite often.<\/p>\n<p>So, &ldquo;today I learned about sockets&rdquo;.<\/p>\n<p>I'll show you how you can create two sockets that communicate with each other.<\/p>\n<p>In order to do this, let's open two Python terminals,\nand put them side by side.<\/p>\n<p>I'll walk you through the things you have to do,\njust make sure to write each piece of code in the correct REPL:<\/p>\n<ul><li>one will be the &ldquo;server side&rdquo;; and<\/li>\n<li>the other will be the &ldquo;client side&rdquo;.<\/li>\n<\/ul><p>To create the server, we<\/p>\n<ul><li>create a new socket;<\/li>\n<li>bind it to the localhost and a random port number (I like 7342);<\/li>\n<li>start listening on that host and port; and<\/li>\n<li>accept an incoming connection:<\/li>\n<\/ul><pre><code class=\"language-py\">## (SERVER)\n&gt;&gt;&gt; import socket\n&gt;&gt;&gt; server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n&gt;&gt;&gt; server.bind((\"localhost\", 7342))  # 1\n&gt;&gt;&gt; server.listen()  # 2\n&gt;&gt;&gt; client, address = server.accept()  # 3<\/code><\/pre>\n<p>At this point, the code hangs because we are waiting for a client to connect.<\/p>\n<p>To create a client, we do the exact same first step, but then we connect to the host and port:<\/p>\n<pre><code class=\"language-py\">## (CLIENT)\n&gt;&gt;&gt; import socket\n&gt;&gt;&gt; client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n&gt;&gt;&gt; client.connect((\"localhost\", 7342))  # 4<\/code><\/pre>\n<p>At this point, the server side is no longer hanging, because a client connected\nand the connection was automatically accepted.<\/p>\n<p>Now, either side can send the first message.\nIf this were a communication through an established protocol,\nwe would know the socket that is expected to send the first message.\nFor example, on the web, with the browsers,\nbrowsers are expected to send the first message (the request) to the server.\nOnly then the server replies.<\/p>\n<p>For our toy experiment, let's have the client send the first (and only)\nmessage with some data, which the server will give back in reverse.<\/p>\n<p>Sending the data means calling the method <code>.send<\/code>:<\/p>\n<pre><code class=\"language-py\">## (CLIENT)\n&gt;&gt;&gt; client.send(b\"Hello, world!\")  # 5\n13<\/code><\/pre>\n<p>Now that we sent some data, the server can receive it and handle it.\nIn our case, we receive the data, and then return it reversed.<\/p>\n<p>After we reverse the data and send it back, we close the socket.\nIn our toy example, we assume that...<\/p>","summary":"Today I learned the basics of socket programming (in Python).","date_modified":"2025-07-23T16:49:02+02:00","tags":["networking","programming","python"],"image":"\/user\/pages\/02.blog\/04.til\/019.sockets\/thumbnail.png"}]}
