Python Socket Programming Tutorial
Key Takeaways
This video tutorial covers the basics of socket programming in Python, including setting up a server and client, handling messages, and implementing a protocol for disconnection and reconnection. The tutorial uses Python 3 and the socket module to demonstrate how to create a socket server and client, and how to send and receive messages between them.
Full Transcript
hello everybody and welcome back so in this video what we're gonna be doing is talking about socket programming in Python now what we're gonna do and the goal of this video here is gonna be to create an application where we can have multiple clients connect to a server and communicate with the server so I'm not gonna be doing anything crazy complex we're not gonna go any into anything that's too specific the objective is to give you the fundamental skills and understanding of how sockets work so that any application or project you want to use sockets in you at least have a really good starting point to do that and you're not kind of lost on how you get the initial setup done that's kind of where a lot of people get confused here is their sockets not connecting properly or they're getting all these kind of issues so I'm gonna go over some of the common problems that I've run into is sockets as well to hopefully kind of mitigate those for you guys we're gonna get started right away by actually just discussing a kind of basic overview of networking so networking is very important to understand when we're dealing with sockets because a lot of the time will actually be wrong is nothing with your code but something with your understanding of the networking or the understanding of your local network so for this tutorial series we're gonna be running this server and this client just on our own computer and our own local network what that means is anyone on our local network so our router right you're your Wi-Fi network will be able to access and communicate with this server but anyone outside of that will not what I will do at the end of the video is show you and steer you in the right direction on how you can get this to work publicly over the internet which means that anyone from any computer in the world can connect to your server but that again is going to come near the end and you need to understand the difference between say a local area network and a public network and kind of how these networking things operate so that you can understand what it is that I'm doing here so anyways let's go ahead and get started I'm gonna discuss the client-server model and then a basic overview of networking so sockets work on this client-server model now what that means is we have one central location or one central process is what I'm gonna call it which is called our server now if we're talking about large companies like Google obviously we know that they have milli or you know even actually probably tens of millions of servers and our purpose we're gonna deal with one server but just know that a lot of the stuff we do with one server we can expand into multiple servers fairly easily just by changing the code up a little bit but in our example we're going to deal with one server so the idea behind the client-server model is you have a central location which we're gonna call the server and then you have all of these clients that are kind of scattered all over the place they're different devices there are different computers they're different networks they're all around the world right and these are what we call our clients now a good example that I typically like to talk about is games because these are things that people have played a lot in it's a very good example of socket programming um not that games always will implement socket programming but it's a good illustration of the client-server model when we talk about a game the client and you've probably heard this in gaming before is your game it's the instance of your game running on your computer so let's use the famous example of fortnight if we're talking about how fortnight works in terms of an online game they have their central servers and then they have all of these clients that are around the world the clients are you you are playing the game you are a client now obviously you do not connect to another client's computer in fact that would be a large security risk if you connected directly to say you know your competitor who's you know around the world you connected to their computer what you do is you connect to the central server that hosts all of the clients that are playing in your game or in your region or whatever it is and the reason for that well there's a few different ones obviously a central location is gonna be faster in general than each client connecting to each other clients computer because if we're playing game of a hundred people I can't connect to every single one of these computers and still have things working properly but that's kind of the concept behind this another idea is that say we're playing a game and I connect directly to the other client well that means I can cheat very easily because I can just send the client false information about my game state that's pretty easy to do and in fact in most games you can probably falsify your game state very easily it just won't work because of the way that the server is set up so we have this server in place to kind of handle and do all communication between these different clients so the server connects to each individual client and then each client connects to the server and what happens is messages are passed between the server and between the client so let's say I have my little character here right and he decides he's gonna move over to the right well that is passed to the server in the form of some kind of command or some kind of message protocol which we'll talk about in a second to tell the server hey I moved to the right now to make sure that this client is not cheating or falsifying its information there's a few things that can happen on the server to do that it can check previous states you can check speed it can make sure that the client is sending accurate information and that is kind of what I don't know maintains this secure idea behind this client-server system I hope that's giving you a little bit of an idea of what I mean but the idea is that you know it sends its movement to the server and then the server transmits that information back to every single client and says hey you know client one moved to the right everyone should know that so you can update that on your end and you can see that and that's the idea behind the client server system so in our example we're gonna have multiple clients connecting to the server they're gonna be sending messages to the server and the server will list out all of the messages so that we can see you know when these messages came in and how they came in and all of that okay so that's the idea behind the client-server model now obviously in an online game we're gonna be connected to a server that is somewhere around the world so that means we're gonna connect over the Internet right but in our local network things happen a little bit differently and we need to understand how our local network works to understand how the internet actually operates as a whole so when we talk about our local network what we have is a few different components we obviously have the most vital component I would say I'm gonna try to draw kind of a crazy version of this which is our modem now what the modem does and typically actually the modem will be wired in to your internet connection right so if you want to install a modem like a Rogers modem or a bell modem or something like that you typically need a technician to come to your house and run a wire into this modem that connects it to the internet now these wires will go to some large cell tower you might have a satellite dish on your house I don't know exactly how you are in and out operates or how it works it might connect to a fiber optic line it might do something like that but the idea is this cable goes to your modem and gives your modem access to the Internet so then what do you do well now they kind of have these modem router things that are combined but typically you're gonna have a router so your router maybe looks like this it has some antennas off of it whatever and we'll call this the router and the router is what actually allows devices in your home to connect to the modem so it plugs into the modem and the router transmits these radio frequency waves or whatever waves they are and you're able to connect to the router wirelessly right obviously you can connect wired as well if you have an Ethernet cable but the idea behind a router is to allow you to wirelessly connect to your network so maybe I have like my phone up here maybe I have a computer or some device like these boxes are just gonna be random devices and the idea is that all of these connect to the router in some kind of way some kind of protocol and then this router communicates with the modem gets information from the modem the modem says okay what information do I need it asks the internet for that information so it pings the satellite or whatever information comes back sends it back to the router the router sends it back to whatever client was asking for that information so that's how this works on your local network so there's something called IP addresses now obviously so your modem is given one what we call public IP address so a public IP address excuse my handwriting this has one so times one public IP address for your modem that represents your physical location in the internet right your physical location on the world that's your modems IP address it's that's important and then you just need to know that then within your local network you have what's called a local IP address so that so because your router needs to be able to differentiate between the different devices on the network so it can know which device to give information back to or to look information up for it needs to know or have some number that represents each of them so you may have seen an IP address that looks like this 192.168.1 maybe it was a dot zero maybe it's not two depending what you're doing and then like 176 right something like that well each device on your local network is given one of these IP addresses okay so that's something to understand we have these local IP addresses that's the way the router communicates with each device on the network and then we have the public IP address which is given to the modem which is the way the modem communicates with the internet and every time that you want to make a search on the internet you go through this process of pinging the router router pinging the modem modem pinging the internet internet giving it back to the modem giving it back to the router and giving it back to you that's the process that you go through and the reason you can do that is because you have this IP address so you can be differentiated on the network as an individual device now and you have access points gets a little bit more confusing but anyways that's the basic idea behind networking I could be butchering this slightly I'm not an expert in this field I'll make that clear but just understand that this local IP address which we call the ipv4 address is different than the public IP address so if I decide to run a what we call server off of a local IP address what that means is any other computer on this local network so that's connected to my router we'll be able to see it and access it right because if I'm connecting and running a server on this device it's connected to the router which means any other device is connected to the router can access this but anything that's not connected to this router so on a different network cannot see that so that's important to understand however if I decide to run a server on my public IP address so from the modem right then what that means is anything around the world can connect to this because it's running on a different IP address so that's the idea behind networking and behind this client-server model I hope that makes sense what we're gonna do is run our networks on or run our servers on our local IP address but later again I will show you how to do that on the public IP address all right so now we're ready to actually start writing some code so we're gonna start by programming out the server and we're not really gonna be able to test a lot of this code until we write a bunch of it so I'm gonna be explaining through exactly what I'm doing to make sure you understand but just kind of follow with me even though you're not wondering if something's gonna work it or not because we really can't test this until we do a significant amount of the code that we actually need to write so notice that I mean yes code now I'm gonna recommend that you use an IDE for this tutorial series so I'm a PI charm vyas code maybe using like some NetBeans thing or something I don't know whatever ID you're gonna use because we're gonna have to run multiple instances of Python we're gonna have a server running and we're gonna have a clients running on our own computer we'll test it on another computer later on but for the purpose of actually you know testing and working this out and all that we're gonna do it on the same computer so the first thing we're going to do for our socket script and notice I should have a server dot PI and client up PI script doesn't matter if they're in the same directory or not is import socket and import threading now for any of you that don't know what writing is threading is essentially a way of creating multiple what we call threads within one Python program so typically if I did something like you know if I import time I did something like time don't sleep one and then print hello like that then we would have to wait for this time not sleep to finish so this wait we had up to wait one second before we were able to print hello but if I run each of these pieces of code in say a different thread what that means is well one piece of code is waiting or it's not doing something the other piece of code or the other thread can run so we're actually gonna put all of the kind of message handling stuff in separate threads for each client that connects to our server so that a client is not waiting for another client to say send a message or receive a message or something like that before it's able to access the server and communicate with the server so we'll talk about that more when that happens but just kind of follow along that a thread allows us to separate code out so that it's not waiting for other code to finish before it's able to execute all right so the first thing I'm going to need to do is define a port so when we run a server we need to pick a port that we're gonna run it on now it's kind of tricky to explain what port to run on the port that I typically run on is 50/50 I don't know the exact numbers of all the ports and what they do but I'm pretty sure above a certain threshold maybe above port 4000 all of those ports on your computer become inactive or not used I think there's something like 10,000 ports again I don't really know you're gonna have to look up the specific information if you want but a safe bet is usually to run on port 5050 this is just because we're trying to pick a port essentially that's not being used for something else a common example of a port is something like port 8080 or port 80 those are HTTP boards I believe which means that is your communication with like websites or with web browsers anything that's communicating over HTTP which is essentially the entire Internet has it now okay so we're gonna do port equals 5050 and then we're gonna say server equals now here we have a few different options so the first option is to go to your command prompt and to type ipconfig and i a lot of people in previous videos like oh you show me your IP address typing IP config does not show you my public IP address so don't worry about that this shows the local network information so if you go on your command prompt or if you're on Mac I think it's ifconfig and not IP config if you're on Windows you can find something that says ipv4 address now what that stands for is your local ipv4 address you can see that I'm connected to Rogers internet here right and this is my local ipv4 address so I'm gonna copy this 192.168.1.2 6 copy that and I'm gonna paste that in here as my server the reason for that is because I want to run this on my local network off of this device this is the device the server is gonna run on so I need to choose the IP address of this device if you try to pick a different IP address that it can't access that is not going to work now another way to do this just type the same line again is to actually type server equals and then in this case you're gonna say socket dot get post by name so I guess this is actually get host by name and then in here you're gonna say socket dot on here get host name no sorry I decided to look at my other screen to make sure that was right but what this block of code actually does is get this IP address automatically for you so let's say we want to run this server on a different device if we just hard code this IP address in then we're gonna need to change that every time that we move this script over so what I typically like to do is this option that I just wrote so we essentially say socket get host my name and then socket get host name if I can get this autocomplete thing to go away what this means is the IP address of this computer by name and then we say okay so what is the name that we're gonna look up well that is the get hostname which is just the name of our computer you can print out these two lines if you want to see what they do in fact let's actually just do it if I print out server and I run this here we can see that we get 192.168.1.2 six and if I decide to just print out this line here we can see that what this actually gives us is in this case desktop r6k and okf so it's just some name that represents your computer on the network so we're saying get the pretty much IP address by hostname and then get hostname so it gets up for us so anyways that gives us our server okay so now that we've determined the port and the IP address that we want to run this server on we need to actually make a socket that's going to allow us to open up kind of this device to other connections so the first step is pick the port and pick the server and then pick the socket and bind the socket to that address so what I'm gonna do is I'm gonna say server and lower case this is equal to socket dot socket like this is how you make a new socket and the first argument here is actually the family of socket that we want now family kind of stands for category that's the way I like to describe it and there's a lot of different categories that we can pick now the types are typically prefixed with a F like this and you can see when I type socket socket and then socket AF the first option is inet which is actually what we're gonna use this pretty much tells the socket what type of IP address or what type of address are we gonna be accepting or looking for for specific connections so you can see that I can pick i net 6 which i believe stands for ipv6 addresses instead of ipv4 and then there's things like packets bluetooth and that link you can do file objects there's all kinds of different sockets you can create so in this case we're a new socket AF underscore eye net and then what I'm gonna do in here is say socket dot stream or I believe it's dot sock underscore stream I'm not really gonna discuss exactly what this means is kind of the standard option but it means we're streaming data through the socket there's different ways of sending data through socket but again that gets into more advanced networking protocols which I don't really cover right here so this one we've done we've created our our socket now we picked the type so we've said it's an AFI net which means over the Internet and then we pick the method which is sock string and I actually sorry this is family and this is type I mean you can kind of think of this as the type of socket as well but it just specifies the type of addresses that we're looking for okay so now what we need to do is actually bind this to an address so what we're going to do up here is we're gonna say a TDR in all capitals and notice I'm doing all capitals just because these are constant values I'm gonna say abd are equals and in this case we're in type server port so when we bind our socket to a specific address it needs to be in a tupple so it needs to have the server first and then the port in which that server is running off of so when we bind this now we can say server dot bind like that and then simply put a TDR in here which now means we've bound this socket to this address so anything that connects to this address now will you know hit this socket that's essentially the objective okay so we have that and now what we're gonna do is see how we can actually make this socket get set up for listening and just print out a few things and let it wait for new connections so I'm gonna zoom out a little bit here and what I'm gonna do is define I want to zoom in one more I want to say defined handle client as a function we're gonna put in here address and then we're going to put connection like that or actually will put connections of con comm and then a TDR and then we'll just simply put pass and then we're going to say defines start so start is just going to start the socket server for us we'll just make it in a function to make things a little bit cleaner so we'll put start and then we'll simply put pass in here so at the bottom of my program what I like to do is call start and right before I call start what I want to do is sprint and say starting I like to just make some nice output here and say server is starting just so when we look in the console we can see kind of what's happening in this case the server starting okay so inside of start here what I'm gonna do now is essentially write the code that's going to allow our server to start listening for connections and then handling those connections and passing them to handle clients which will run in a new threat so what I'm gonna do is I'm gonna say s naught s server dot listen which means okay we are now listening for new connections we'll set that up and then we're gonna say wow true because this is gonna go in an infinite loop essentially it's gonna continue to listen until you know we don't want to listen anymore until the server crashes or until we execute it or turn it off I'm gonna say while true say server dot accept like that but here we're gonna say a TDR connection equals server dot connect and I think that's right actually I've messed it up it's con comma a TDR and the reason for this is essentially what this line of code does is it's it it blocks and what that means is this line will wait like we'll wait on this line of code here for a new connection to the server when a new connection occurs we will store the address of that connection so what IP address and what port it came from and then we will store an actual object that's going to allow us to send information back to that connection so that's what con stands for you can see that it's giving me socket here unused variable connection so this is actually a socket object that's going to allow us to communicate back to the connection or the thing that connected and this is simply just the information about the connection so what port and what IP address connected to the server so when that happens what I'm gonna do is start a new thread which is equal to handle client so a thread of this function and this function here will handle all of the communication between the clients in between the server from now on so this little function here is meant to simply handle new connections and kind of distribute those to where they need to go whereas here will handle the individual connection between the client and the server so one client and one server so what I'm gonna do is I'm gonna say thread equals spreading dot thread this is the threading module in Python 3 by the way so if you have Python 2 this likely will not work for you and I say target equals in this case the name of the function so handle clients no brackets notice I don't have any brackets there I'm gonna say args equals in here con a TDR so essentially what I'm saying is okay so when a new connection occurs we are going to pass that connection to handle clients will give handle clients so we'll say target is handle client right this new thread that's what that means arguments are what arguments are we passing to the function so in this case connection and address and then we'll simply start the thread so thread start like that now I often like to see how many active connections we have on the server so what I usually do is after I start a new thread is simply print the amount of active connections currently just so that we can see that so what I'm gonna do here is I'm going to say print and we'll just do a print a new line here and we'll say active connections like about an all capital I'll make this an F string and then we're simply gonna say reading dot active like this active count minus 1 now what this tells us is how many threads are active on this process or in this Python process the amount of threads will represent the amount of clients connected because we will create a new thread for each new client but since there's one thread running always which is this start thread to listen for new connections we'll subtract one which means that this will tell us there is one active connection when there is two threads running right that's the idea we might need to move this line of code later but for now we'll leave it here and then we're now going to start handling handle client so since handle client is in its own thread this is gonna run for each client just remember this function will be running in parallel and on parallel really but kind of concurrently for each client so the first thing that we're gonna do is simply print a new connection so we're gonna say print and then new connection like that and then here we'll do another half string and we'll say who connected so we'll say a TD are connected just so that we get some information in our server the next thing that we'll do is we'll set up a while loop and we'll say while true actually we'll say connected equals true and we'll say while connected like that so while connected then here we're gonna wait to receive information from the client and when we receive information from the client we're gonna do something with and simply printed to the screen so what I'm gonna say is message equals and then in this case we're gonna say con like that dot our CV so dot receive and then we actually need to put in here how many bytes we want to receive from the client now this is gonna bring us into talking about message protocols which we're gonna do in just a second but the idea here is this line of code again is what we call a blocking line of code which means that we will not pass this line of code until we receive a message from our client so that's why it's important that we have these and threads to make sure that we're not blocking other clients from potentially connecting because these lines socon dot receive and server dot accept are blocking lines of code so receive is saying okay we're gonna receive a message from the client we receive that from this socket like that which means wait till something is sent over the socket but what we need to put in the brackets here is how many bytes we are going to take so how many bytes we're going to accept now how are we gonna know that so the idea behind how many bytes is like we might send a message like hello to the server but we might also send a message like hello like that to the server right and clearly this message is a lot longer takes up more bytes than the other message so how are we gonna know how many bytes to receive from the client sorry not the server if you know if we're just guessing right we need to come up with some kind of protocol some method of sending messages that tells us how many bytes we're gonna be receiving so what we do is we create what's called a header now I'm going to talk about what a header is in a second but we're gonna do up here is define a fixed length header of what we're gonna call 64 bytes now what this means is what we're actually gonna do is the first message to the server every single time from the client is going to be a header of length 64 that tells us the length of the message that's gonna come next so essentially we're gonna say all right since we don't know how big a message is gonna be we're gonna say that the first message to the server every single time needs to be a message of length 64 what that means is that it always no matter how big this message actually is it needs to be like 64 right so we'll have to do that the client-side later but just know that the header size were picking is 64 and these 64 bytes that we're sending are going to have a number in them that represents the length of the amount of bytes for the message that we're about to receive so essentially say we're gonna send the message hello this isn't really 5 bytes but say this is 5 bytes the first thing we'll send to the server is 5 and we'll pad that message so that it's 64 bytes long and then we'll read that we'll say okay so we're gonna be receiving the number 5 so we're receiving 5 bytes of information and then we'll receive again 5 bytes so that means we'll send this first message receive it on the server and the server will wait to receive now the next message which will be of length of whatever it's sent in the first message this will make more sense once we get through it but hopefully that gives you an idea of what I'm trying to accomplish here so the first thing that we're actually gonna say is message length because we're gonna follow this protocol write is going to be equal to Khanda receive and then header now hetero means 64 the only issue with picking a fixed length header this small is that if we send a message that is actually essentially we need to be able to represent the length of the message that's gonna come with 64 bytes now I actually don't know what that means in terms of the actual numeric value but if we were sending a really large message we may potentially run into the issue where our header is actually too small to represent the length of the message that's about to come we won't in our example but just keep that in mind that is a potential concern of the way that we're doing things okay so what's a message length equals con dot received header and then what we're gonna do is actually decode this because every time we send a message we need to encode it into a byte format and we're gonna encode that with a decode that with a UTF form so I'm gonna say format up here equals and then here gonna say UTF - 8 just so that we have that is a constant we can change that later if we want so we'll say decode format which essentially means decode this message from it's bytes format into a string using utf-8 and then what we're gonna do is convert that to an integer so we're gonna say okay so message underscore length like that equals an int of message length and then we're gonna receive the next message so we'll say the actual message is going to be equal to con dot receive and in here this is gonna be message length same thing decode format like that if I could type Y my typing so horribly Jeanette formats there you go so con dot receive message length decode format so the first message tells us how long the messages that's coming so we use that convert it to an integer and then put that in here as how many bytes we're gonna be receiving for the actual message so then we should know that this message is accurate so what we can do is simply print in here and we'll say put an F string I'm just gonna put a TDR which is the address of the person and then what they said so in this case MSG so we received a message from them we'll print out a TDR in brackets and then whatever the messages that they sent now an important thing that we need to do is actually handle how to close a connection so we want to make sure that when a client leaves there's some protocol that we've come up with to make sure that we handle their disconnection cleanly so yes they could just disconnect and not tell the server that they're disconnecting that wouldn't really cause that many issues but when they want to reconnect later we might run into a problem that the server already has them connected and since they didn't cleanly disconnect when they try to connect it's gonna say hey we can't connect you because on our end it seems like you're already connected even though they may not be so the way that we do this is we come up with some kind of message that we send to notify the server that we're gonna disconnect so in this case we're gonna call this the disconnect underscore message and we're just gonna make this a exclamation point and then disconnect now you can make this message whatever you want but this means when we receive this message we will close the connection and disconnect the client from the server so to do that we're gonna say if here so if MSG equals equals disconnect message then we'll simply say break or we can say connected equals false right we do what everyone we want I'll just do connect that equals false and then yeah we can print out the disconnect message that's fine then we're gonna say ISKCON dot close what that means is close the current connection cleanly disconnect everything should work fine and in fact yeah that should actually be fine and I think that might be the server completed let me just look and make sure that everything is fine here I believe it actually is and we're good to go all right so this is the server the server is complete let me show you what happens when I run it you can see that we get server is starting like this now what I'll actually do is I'll close that right now we'll add one more line just to tell us what what IP address the server is running on just so we know so after we start listening we'll say print we'll say I don't know something like this listening so server is listening on and then in this case we'll put the IP address we'll say F string and then here we will do server like that just so we can see what IP address is actually running on will do server and that should be it for the server let's run this and see server is listening on 192.168.1.2 6 so this should work for all of you guys again you don't need to install any packages or anything I know I didn't mention that but when you run this if you're getting an issue recheck your code look at what I've done here because chances are you typed something wrong or you have a firewall or something on your computer that's not letting you run this if you're getting an issue in it's saying like some socket issue like you cannot run on this support or whatever it is or cannot run on this IP address then make sure you disable any firewall on your Windows Explorer all right or your windows whatever you want to call it I don't know Windows Defender because that may be causing the issue but anyways now we're gonna move on to the client and see how we can actually connect to the server so here we're gonna import in this case socket and then I don't actually don't think we need anything else on the client sign so we're gonna define some of the constants we've had before so we're gonna keep the header of 64 we're gonna keep the port like that so let's go header port we need this format and this disconnect message so let's copy those and then what we need is obviously the server now the server here will change depending on what server we're connecting to so in this case we're gonna connect to 192.168.1.2 6 again remember this number will likely be different for you it will probably not be to 6 it will be whatever your ipv4 addresses that you found from terminal or from the command line but you can always write this line here which will give you the IP address of your actual machine right so that will tell you which one you will be able to run on and then if you print that out you can see that and type that in here okay so we have that now all I'm gonna do is set up the socket for the client so we've done this already pretty much we're gonna say socket equals socket dot sockets in here we're gonna say socket dot AF underscore eye net if I could spell socket correctly that was just a butcher then we'll say socket again dot in this case sock underscore Street okay so we'll do that and now we have the socket set up here and now we need to connect to the server so to do that what we're gonna do is say sockets and I can't name the socket what am i doing name that client - my apologies guys client dot connect so notice instead of bind we're connecting now in this case we need to define a DDR up here again so a DDR equals in this case server and port so we'll connect to a TDR like that and now we have officially connected to the server so actually let's take a pause here and test this and see if this is working when we connect because notice I print new connection right connected and that should actually show up and we should see that so let's run the server make sure that the server is running a common issue is people don't have the server running and they try to connect and it doesn't work I mean obviously yes that's not going to work when you try to connect to a server that's not running now what I'm gonna do is just go on my command prompt because I don't think vs code lets you run multiple python interpreters at the same time although I could be wrong let's see D into socket tutorial like that and let's go python in this case this was client so when we do that we get invalid literal for int with base 10 in handle client okay so that's alright let's just have a look here okay so what we're gonna do here is just make a quick fix on the server because you saw that message that was popping up it was saying invalid literal for into a base town I guess it's not popping up anymore because I closed the server but it was saying invalid liberal four inch with base ten and the reason for that is when we connect a message is sent to the server telling us that we connected but what we're doing here is we're trying to handle immediately the message that's being sent with the length of the messages about to come which we haven't yet sent so we need to make sure that we're getting a valid message before we try to convert that message to an integer because otherwise we're gonna run into an issue so what I'm gonna do is simply just say if message length which simply means if this message has some content because essentially when we connect when we receive will receive nothing the first time because when we connected the message is it's kind of it's difficult to explain exactly why this happens but when you connect some kind of message is sent it's not really a valid message is kind of like a blank message so when we try to convert that into an integer we run into an issue so we're just gonna make sure that we get an actual message here by checking if this is not none that's what this line means here and if it's not none then we'll do this protocol that we talked about before so let's run this now let's rerun the server server's listening on that port okay so let's go here let's run this and notice that we don't get an issue this time we get active connections one 192.168.1.2 six connect button awesome okay so now that we're connected to the server what we actually need to do is come up with a way to send eight messages so we're just going to start by creating a define send function we're going to take MSG as a parameter we're gonna start by saying message equals in this case MSG dot encode in format now this is because when we send messages we need to encode them into a bytes format so what encode actually does let's see if it gives me that pop-up it's not of course is encode this string into a bytes like object so then we can actually send the bytes through the socket and that's you know working that's how we have to do that now if since we need to follow this protocol where the first message we send is the length of the message that's about to come we need to get the length this will say MSG underscore length equals in this case the land of message and then what we're gonna do is we're actually going to encode this as a string so we're gonna say send length equals in this case STR of message underscore length like that dots in code we're going to encode that with the format of utf-8 then what we're gonna do is now pad this to make this length 64 so right now the send length which is the first message that we're gonna send representing the length of this message right the one that we actually want to send we need to make sure that that message is 64 bytes long so we don't necessarily know that it's gonna be 64 bytes long because it's just gonna be some integer that we're sending maybe it's like 5 10 20 whatever it's telling us the length of the bytes that doesn't mean that the message we're sending is that long so we need to now find the length of this message we need to take 64 and subtract this from 64 to figure out how much we need to pad this so that is of length 64 so we're gonna say padded send the length is equal to in this case send underscore length actually I guess we can just do we could just do this we could just actually add this padding so send underscore length plus equals in this case we're gonna say B and then we're gonna do a blank string with this space now what this means is the byte representation of this string so since we just want to add blank spaces just we want to add padding to make it the correct length we can just add a space so we'll say B and then a space sentence for byte space x in this case we're gonna say header minus the Len in lower cases of send length so we're gonna get the length of this we're gonna subtract it from the header and then we're gonna add that amount to this so that it's like 64 then all we need to do is say in this case client dot send send length then client taught send in this case it's gonna be that message so this should hopefully work so we can try this when you send Hello like that actually seduced to hello world so we can see how that works I don't think the service still running I'll reboot it it is still running so actually let's just reboot that now so we see the server is running let's go to our command prompt let's go and run this client script and we see that we get active connections 1 and HelloWorld popping up that actually means that we did this correctly what happened was this is the server script notice that that happened when I pressed enter here we were able to send that text we decoded that on the server side and then that was printed and shown so I can actually send more than one message obviously if I would like so let's now handle the disconnection message that's kind of next I'll shut down this server we're gonna send the disconnect message and see what happens now after we send HelloWorld let's send a few more actually so send hello everyone hello Tim like that so let's run this server now and then run that and see what happens when we send that disconnect message so we go here a new Python client up hi hello world hello everyone hello Tim disconnect and then we've disconnected from the server and if we decide to reconnect again which we can totally do by just running this script again we will see that the active connection is one it's not 2 because we actually exited that thread and got rid of it when we saw that disconnect message so that's the basics behind sending those messages so now what I'm gonna do is show you how we actually connect with multiple clients and how we can make it for example if I just do like input like this you have to press space to send it so let's do that actually first and show you how that works so input like that here we go now if I run clients we'll see that it shows whole world when I press ENTER it shows hello everyone enter again hello Tim disconnect that's great so let's run an instance of client there we're gonna run one more in another command prompt if I could get to the folder so CD socket tutorial Python client PI and then notice we now get active connections too it's saying hello world from someone else if I go to this script and I hit enter it says hello everyone and notice that's from a different number than this number it's the same IP address because it's the same computer but it's giving us a different port number actually I don't think that's support number but something anyways and if I now go from this one and I hit enter if I can get that in here what's happening on this client script something's going wrong here uh enter there we go gets hello everyone hello everyone come here hit Enter disconnect come here hit Enter disconnect so we know multiple clients connected it doesn't matter when they're sending messages these will still work fine I don't know why I had the bug before I think it was just this command prompt window is glitching out but that is the basic idea behind this client-server system and sending and handling messages okay so now I've shown you how we can send messages from the client to the server but how about from the server to the client what's actually quite easy and in fact it's the exact same thing except just going the other way so if we want to send a message back to the client what I'll do is I'll just implement in here a simple sent so we'll literally just go Conn dot send and here we can say something like I don't know message received if I can spell receive properly I don't even know if that's right any more dots in code format so all we're gonna do is simply send this message encoded with that format so every time that a message is sent to us we will encode that message and send it back now to see that sending back oh I've already added this in here forgot that I put that there when I was testing in between the break what we can do is merely write print client dot receive and then some number in here ideally we would use the same protocol we've used to send a message to the server to send one back to the client so that fixed-length header but because I'm lazy and we're getting near the end of the video I don't want to do that you guys understand how that works so I've just put a large number here to make sure that we'll be able to handle whatever message is sent back but the idea is after we receive a message we will send back to the client a message and then they can receive that by writing client receive if this number is long enough obviously they will be able to receive the length of the message we will print that out in fact we can actually decode this to make sure this is not byte formats or decode and then we'll put format like that and then we will see that messages received every time that we a message and if we don't get that message received that means something was wrong on the server side now a lot of you are probably saying and I'll show you this how this works in a second well what if I want to send the messages from the other client to the other client to do that what you would need to do is store a list of all of the messages below believe that are sent so essentially every time a message is received from client 1 what you would need to do is add that to a list and then what you would do is send that back to each client so if you want to do that you can make another like protocol or another I don't thread that does that so send to every single client or what you can do is check in a specific line itself what messages it's up-to-date with so you can say okay um have you seen the previous message that this person sent in that person sent if they haven't you send it to them right there's different ways to do this that's when you start getting into more complicated things in sockets but the idea is right you know we can send things from the server to the client the same way that the client can send things to the server so let's run this let's go server see what's an issue here we run into something let's just do this one more time okay so server is listening let's go to our command prompt let's run a Python client PI and notices says msg received so we hit enter message received again message received disconnect boom everything is working we are good so that is how that works in terms of sending messages back now if you want to send something that's not a string so you want to send say like an object then what you can do is you can send messages that are JSON serialized or you can send messages that are pickled now I forget the way that pickle works totally so I'm not actually gonna show you but the idea is you can import pickle and you can look this up there's tons of stuff online that shows you how to do this you import pickle you can pickle like a Python object so an entire objects like you make your own custom object you can pickle that which is a way of serializing it and then send that through the socket back to the server where the server can unpick lit and use it so if you want to send things that aren't strings that's a way that you can do it typically we're just gonna be sending strings which is what I've shown here but this should hopefully give you enough information to make some kind of socket applications again I know a lot of you are gonna want to send messages between clients so the way to do that is to globally keep track of all the messages that are sent and then within the thread here right you're gonna check if you need to send messages from other clients to the current client and you can also do something like a constant ping command so you can have the client constantly send the server like a read r
Original Description
This socket programming tutorial will show you how to connect multiple clients to a server using python 3 sockets. It covers how to send messages from clients to server and from server to clients. I will also show you how to host your socket server locally or globally across the internet so anyone can connect. This uses the python 3 socket and threading module.
Code Download: https://techwithtim.net/tutorials/socket-programming/
◾◾◾◾◾
💻 Enroll in The Fundamentals of Programming w/ Python
https://tech-with-tim.teachable.com/p/the-fundamentals-of-programming-with-python
📸 Instagram: https://www.instagram.com/tech_with_tim
🌎 Website https://techwithtim.net
📱 Twitter: https://twitter.com/TechWithTimm
⭐ Discord: https://discord.gg/pr2k55t
📝 LinkedIn: https://www.linkedin.com/in/tim-ruscica-82631b179/
📂 GitHub: https://github.com/techwithtim
🔊 Podcast: https://anchor.fm/tech-with-tim
💵 One-Time Donations: https://www.paypal.com/donate/?token=m_JfrPK7DsK4PLk0CxNnv4VPutjqSldorAmgQIQnMozUwwQw93vdul-yhU06IwAuig15uG&country.x=CA&locale.x=
💰 Patreon: https://www.patreon.com/techwithtim
◾◾◾◾◾◾
⚡ Please leave a LIKE and SUBSCRIBE for more content! ⚡
⭐ Tags ⭐
- Tech With Tim
- Python Tutorials
- Python Socket Programming
- Socket Programming Python
- Python Sockets Multiple Clients
- Socket Tutorial Python
- Python 3 Sockets
⭐ Hashtags ⭐
#python #sockets
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Tech With Tim · Tech With Tim · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A* Path Finding Algorithm(Visualization)
Tech With Tim
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
Python Programming Tutorial #3 - Conditions
Tech With Tim
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
Python Programming Tutorial #6 - For Loops
Tech With Tim
Python Programming Tutorial #7 - While Loops
Tech With Tim
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
Python Programming Tutorial #10 - String Methods
Tech With Tim
How to Overclock a NVIDIA GPU
Tech With Tim
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
Python Programming Tutorial #12 - Functions
Tech With Tim
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
Cool VBS Script to Prank Your Friends!
Tech With Tim
How to Overclock an AMD GPU
Tech With Tim
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
Recursion and Memoization Tutorial Python
Tech With Tim
Ethereum Mining Rig - Hardware Guide
Tech With Tim
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
How to Install Pygame (Windows 8/10)
Tech With Tim
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
Linear Search Algorithm - Python Example and Code
Tech With Tim
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
Binary Search Algorithm - Python Example & Code
Tech With Tim
Pygame Tutorial #5 - Projectiles
Tech With Tim
Pygame Game - Mini Golf
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
Pygame Tutorial #6 - Enemies
Tech With Tim
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
How to Create A Message Box in Python - Tkinter
Tech With Tim
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim
More on: LLM Foundations
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Stop Guessing: Guaranteed Structured Output from LLMs in Node.js
Dev.to · Hardik Mehta
Spring AI Tutorial — Your First REST Endpoint with OpenAI (2026)
Dev.to AI
Notes: Memory, Context, and Large Language Models (LLMs)
Dev.to · Vladimir Panov
10 ChatGPT Prompts for Job Seekers: Resumes, Interviews & Career Growth
Medium · ChatGPT
🎓
Tutor Explanation
DeepCamp AI