Python Online Game Tutorial #2 - Creating a Server

Tech With Tim · Beginner ·🧠 Large Language Models ·7y ago

Key Takeaways

This video tutorial demonstrates how to create a server using Python sockets, handling multiple connections and storing/sending information. It covers setting up a socket, binding the server and port, and handling incoming connections using threading.

Full Transcript

hey guys and welcome back to the second video in my online python game development Series so in this tutorial we're going to be working on coding the server and then in the next video we're going to be connecting this client that we made in the last one uh to that server and then sending information to and from the server uh so let's get started and let's create a new file that is going to be our server file so I'll just call this one server.py and then in here we're just going to have to import a few things and I'll talk about exactly what they're going to do for us once we start using them so let's start by importing sockets uh or socket uh then we can import underscore thread and we'll also import uh OS okay so actually not OS sorry Sy that's all we need for that so what we're going to be doing like I've talked about is we're going to be using sockets and threading to uh handle connections to our server and essentially what that means is we're going to set up a socket and it's going to allow for connections to come into our server on a certain Port so we're going to start by just defining a server which is going to be a string and Port which is going to be a number now for Port um you guys probably know what ports are uh you might have heard of them before for example like a common Port you would use on uh or a common Port that is used like on your router would be Port 80 and that is for HTTP connections there's also a port like 44 three there's there's tons of other ports that have um distinct uses but there's also a ton of ports that don't have any uses and that are just left open for programs like this or for different things to be used for so what port I'm going to use which is typically open um it depends on like what router you're using and your internet connection but typically a port that's open is 5555 um so we're going to use this port to connect to and from and it's just a safe port to use as opposed to trying to use another number uh that we might not know if it's being used for something else or not okay so once we've done that we've created a server and created a port what we're going to do is we're going to set up what's known as a socket okay and we'll talk about exactly how this works in a second um but we're just going to say s equals socket do socket and then here we're going to type something that's probably going to mean nothing to you but I'll talk about what it means so we say socket equals AF _ inet okay and then socket do sock stream like that all right now these are just the types of connection so since we're going to be connecting to a uh ipv4 address which again we're going to keep talking about all this stuff as we go through in case you guys are unfamiliar with networks uh this is the type we're going to have to use and sock stream just I believe represents um like how this server string comes in I could be wrong on that but um this is the type we're going to use and for any kind of applications like this this will be what you use for your socket okay so we're just initializing that and now the next thing to do is to bind our server and our port to the socket so to to do this we need to do a try and accept and the reason we do this is because like I talked about we don't know if this is actually going to work initially doing it there could be in some instance this port is already being used for something and if that's happening that means that this is going to fail so we need to try and accept this so we will accept uh what do you call it uh error as e so what do we say socket dot error as e and we'll just print that out to the screen just so we know why we're not working there uh otherwise what we'll do is we'll say s. bind and then in here we're going to put server comma Port okay so we'll bind to whatever IP address we'll put in here uh to this given Port okay so I hope everything's making sense so far essentially what we're doing when we do sockets is we're setting up um a connection or we're using a port on our server on our Network um it's going to look for certain connections and then we'll be doing this on the client side as well we'll be binding or not I don't know if it'll be binding we'll just be connecting to a certain server and a port um and then since we're connecting to that this server script that we're going to have running we'll see that connection and handle it in some way okay so now that we've done that I'm trying to think what else we have to do okay so what we're going to start by doing is we're going to start listening for connections um so we're going to do s. listen now s. listen essentially just opens up the port so now we can start connecting to it and having multiple clients connecting and whatnot um so in here this actually takes one argument now it's optional uh and if you leave it blank it means it'll allow for unlimited connections to happen now depending on what kind of program you're writing uh is what you're going to do for this now for me I only want two people to be able to connect to my uh what do you call it yeah to my server so we're just going to do s. listen 2 now this might actually be one because it might be like 0o one but I think two may be the correct thing so do s. listen for now uh and then what we're going to do is we're going to print after we listen we'll just say waiting for uh connection and we'll say server started or something like that because once we get to this point we are running the server and everything actually is working like we're listening for connection we're ready to go okay so the next thing we're going to do is we're going to define something known as a threaded function okay and we'll I'll talk about again what this means um but let's just do threaded uh threaded client for now and I'm just putting you don't actually have to name it this you can name it whatever you want I'm just putting threaded here just so we know this is threaded and then it's going to take one argument which is just going to be CN which stands for connection and let's just pass in there for right now so the way that threading Works uh actually let's let's do the threading and then I'll talk about how it works because it'll probably make a bit more sense so let's do a while true down here okay so once we set up uh our server our Port we bind it doing here we're starting to listen waiting for a connection starting the server then we're going to do is we'll be get put into this while loop and what this while loop will do is it will continuously look for connections okay cuz right here we're just listening uh like once right to see if anything's on that server Port but down here we want to continually try to grab connection and see if someone connected and if it does then we want to print something to the screen or we want to send information or we want to start a new thread which we'll talk about in a second so in here what we're going to do is we're going to say connection uh which CNN and then ADR equals and then s do and then we'll say accept and what s. accept is going to do is it's going to well accept any incoming connections uh and then it's going to store the connection and the address and the connection is by the way an object representing like what's connected the address is going to be an IP address in these uh variables okay so if we get a connection uh what we'll do is we'll say print uh connected to okay and then ATR and this is just going to show us what IP address is actually connecting uh so we can have a look at that and then what we're going to do is we're going to do startor newor thread and then in here we're going to do uh what was that name of the function that we had was threading client okay and I believe we do comma and then in Brackets here we do Co like that okay so start new thread is there a reason that's not working um give me a sec guys I want to see why oh that's why so up here instead of saying import thread we're going to say from uncore thread import Star okay and that's just going to make it so we can just do this start new thread thing and you know what I don't know if we're going to need this Sy but let's just leave it there for now okay so let's talk about what threading is going to do so essentially the way that you guys are used to programs working I'm assuming unless you have some familiarity with threading is that uh say we're in this wall Loop right and we were to call the function thread a client well before we continue going with this W Loop we would have to wait until this function was done running in other words we return back from this function some value or uh for example like he does like xal 5 we would have to wait for this xal 5 to execute and then it would come back in this wall Loop and keep going now we don't want that to happen because we're going to be having multiple connections going at once so what we want to do is we want to start what's called a thread and a thread is just another process that's running in the background so that just means when we do start new thread and we do thread a client um it's going to run this function but it's not going to need this function to finish executing before it continues the while loop so this is going to be running in the background as like process two while process one is still running and still going so that means say we connect to 100 different things we're going to have a 100 different functions running so 100 different threaded clients um on the stack are like keep going and then what we're going to have is this this while loop still continuing to go what did I just do um still continuing to run to look for another possible connection you guys will see more how this works but essentially just means this will run in the background and we don't have to wait for it to finish executing before we can accept another connection that that's the basic kind of way to that works so now let's start working with threaded client and then we will uh test the server out and see if it's working and then obviously in the next video we're going to connect to it and do all the connection stuff okay so in here uh threaded client so what should happen when we connect to uh a client well we're going to have to do a while open here so we're going to say while true because we want this to continually run while our client is still connected okay now what we're also going to do is we're just going to say reply equals blank like that I'm just copying from my other screen because this one is a bit finicky I don't want to mess it up we're going to put a try in here and what we're going to say is we're going to try to receive some kind of data from our um connection okay from whoever's connected we want to receive some kind of data so what we'll do is we'll say I believe it's uh escon do receive that might be right yeah I think that's right and then in here we're going to put the amount of bits okay now if you guys know anything about Computing you know like how what bits represents um but essentially this is the amount of information we're trying to receive now if you're getting an error when say you like do this and you connect up and you get some error that says um what do you call it like object was trance or like uh you you're getting any errors just increase this size okay and you can just do that by like putting this like times 8 or something just note that the larger this size is the longer it's going to take to receive information and that's obviously because the more information you're getting the longer it takes to send that over the server so 248 bits is not a lot it doesn't take very long it happens almost instantly but if you bump this number up to a ton then it will take uh longer to do that okay so data uh and we're going to say reply equals and then we're going to say data do I think it's actually string. dcode H let's see this oh data. decode because it'll be in that that kind of object that data. decode and then here we're going to do UTF comma 8 now the reason we have to do this is because whenever we're sending information over a like client server system we have to encode the information and you'll see that in the next step that we're going to encode information before we send it back to the client um but that means that we're receiving encoded information so to actually be able to read it like in a human readable string we need to decode it first uh so it's really easy to do that we just do decode and we're just giving the format which is utf8 okay so reply equals that and then what we're going to say is we're going to say if not data we're going to print uh disconnected okay and then we're going to break and this just means if we try to get some information from the uh what do you call it the client but we're not getting anything We're going to disconnect and we're going to break and that likely means that we've well disconnected from the client or the client's left or something like that so instead of continuing to run this while loop and trying to get information from a client that's disconnected we're going to break this is just kind of a fail safe to make sure we don't get into any infinite loops and it's also going to show us if we're running into any issues with like receiving the data and decoding it which we'll talk about later okay so so otherwise so if we are getting information all we're going to do is we're going to print uh received is that how you spell received maybe uh and then we're going to put what do you call it reply okay uh didn't mean to do that let me see if I'm spelling this right I not okay received reply so this just means we received from the client uh this reply let's print it to the screen and see what it looks like and then we're going to print sending uh colon and we'll just print reply okay and then we'll talk about this again in a second why does this keep happening okay reply next now after this uh if not data break out what we'll do down here is we're going to say con. send all and we're going to send Str str. encode reply now again remember that since we're sending information over the server we have to encode our information so all this is going to do is just encode our string reply into a b object so that means when we read it in from the client side again we'll have to decode that information uh it's kind of annoying but I mean it's security thing right so now we're just going to accept uh I guess what what kind of error would it even be I don't even know if there's going to be any errors if we run into anything let's just break uh just to make sure that we're not you know getting in that infinite Loop or we're not going to ruin the program by doing that okay so this is actually about it for our server uh let's see how much time we're at 13 minutes okay so now what we need to do is figure out what this server number is and then we can actually test it and see if this is working uh so what we're going to do now is we're going to find the server number now to do this we're going to be doing this over uh Local Host okay that means that our we're only going to be able to connect over our local network meaning that like anything on our Wi-Fi network um that can see each other that'll work fine but as soon as we go outside that Network it won't work so we're going to be using what's known as local IP addresses so to find the local IP address of the machine currently on you're going to go to command prompt in the bottom left uh and then you're just going to type ip config okay now um some of you guys are probably freaking out because you can see my IP address right now this is a local IP address and that means that it is locally assigned to my network no one outside of my network can see this IP address or can ping it or can dos it or anything like that okay so it's perfectly fine if you guys see this address or if other people know what this local address is okay just as a note so what we're going to do is we're going to take this ipv4 address so just copy that and we're going to paste that inside of the string here okay so 10.11 25027 is mine now yours likely is like 1 192.168 something okay but since I'm on like a massive Network usually they use 10.10 like as the default gateway which is what they're using so my IP address starts with a 10 yours likely starts with 1 192.168.1 or like five or something like that and then the rest of it okay so that's the address we're going to use and this is going to be our server address so whatever machine that you're going to be running the server script on that's the address you want so say you want to run this server on your laptop uh and you want to run clients on like your PC and your Mac or something like that then you want to make sure you get the IP address from your laptop and you're putting it in that script okay and we'll talk about more of this in the next video when we actually connect to it okay so now that we've done this um I probably made a mistake but let's actually just create a configuration quickly for Server um and run this and just see if we're getting any errors as of now now it is worth noting that we're not going to be able to connect anything yet um so there's not really going to be much we can see or really do uh but for now let's just test this out so let's have server let's run this and you can see waiting for a connection and server started so that's actually good if you're getting this uh string of text everything is currently working uh in the next video we'll probably have to debug a little bit once we start connecting to this but for now that is the main server SC script now I'll briefly just talk about before I end this video how it's going to work in terms of running the server script and running the client script um the server script always has to be running okay so whenever you're trying to connect you have to have first run the server script and then you can run multiple client scripts from wherever on the network you want now the server script has to be running on the machine that the IP address is like this little string here okay it has to be running on that machine um and you can run a client script on the the same machine that the server script's running and you can run multiple client scripts on the same machine so like for example what I'm going to do to test this in the next video is I'm going to run the server and then I'm going to run two clients on uh this machine and we'll see that it like is moving back and forth for them so anyways that's been it for this video as always the code is up on techwith tim. net in case you guys missed any of this or you're running into any issues and with that being said I will see you guys in the next video w [Music]

Original Description

This online game tutorial with python shows how to create a server using python sockets. The server will be responsible for handling multiple connections/clients and storing/sending information. Source Code: https://techwithtim.net/tutorials/python-online-game-tutorial/server/ ⭐ Kite is a free AI-powered coding assistant for Python that will help you code smarter and faster. Integrates with Atom, PyCharm, VS Code, Sublime, Vim, and Spyder. I've been using Kite for 6 months and I love it! https://kite.com/download/?utm_medium=referral&utm_source=youtube&utm_campaign=techwithtim&utm_content=description-only ◾◾◾◾◾ 💻 Enroll in The Fundamentals of Programming w/ Python https://tech-with-tim.teachable.com/p... 📸 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-rusci... 📂 GitHub: https://github.com/techwithtim 🔊 Podcast: https://anchor.fm/tech-with-tim 💵 One-Time Donations: https://www.paypal.com/donate/?token=... 💰 Patreon: https://www.patreon.com/techwithtim ◾◾◾◾◾◾ ⚡ Please leave a LIKE and SUBSCRIBE for more content! ⚡ Tags: - Tech With Tim - Pygame - Python Tutorials - Online Game Tutorial Python
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 A* Path Finding Algorithm(Visualization)
A* Path Finding Algorithm(Visualization)
Tech With Tim
2 Python Programming Tutorial #1 - Variables and Data Types
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
3 Python Programming Tutorial #2 - Basic Operators and Input
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
4 Python Programming Tutorial #3 - Conditions
Python Programming Tutorial #3 - Conditions
Tech With Tim
5 Python Programming Tutorial #4 - IF/ELIF/ELSE
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
6 Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
7 Python Programming Tutorial #6 - For Loops
Python Programming Tutorial #6 - For Loops
Tech With Tim
8 Python Programming Tutorial #7 - While Loops
Python Programming Tutorial #7 - While Loops
Tech With Tim
9 Python Programming Tutorial #8 - Lists and Tuples
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
10 Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
11 Python Programming Tutorial #10 - String Methods
Python Programming Tutorial #10 - String Methods
Tech With Tim
12 How to Overclock a NVIDIA GPU
How to Overclock a NVIDIA GPU
Tech With Tim
13 Python Programming Tutorial #11 - Slice Operator
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
14 Python Programming Tutorial #12 - Functions
Python Programming Tutorial #12 - Functions
Tech With Tim
15 Python Programming Tutorial #13 - How to Read a Text File
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
16 Python Programming Tutorial #14 - Writing to a Text File
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
17 Python Programming Tutorial #15 - Using .count() and .find()
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
18 Python Programming Tutorial #16 - Introduction to Modular Programming
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
19 Python Programming Tutorial #17 - Optional Parameters
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
20 Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
21 Python Programming Tutorial #19 - Global vs Local Variables
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
22 Python Programming Tutorial #20 - Classes and Objects
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
23 Cool VBS Script to Prank Your Friends!
Cool VBS Script to Prank Your Friends!
Tech With Tim
24 How to Overclock an AMD GPU
How to Overclock an AMD GPU
Tech With Tim
25 Best GPU'S For Mining Ethereum (2018)
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
26 Recursion and Memoization Tutorial Python
Recursion and Memoization Tutorial Python
Tech With Tim
27 Ethereum Mining Rig - Hardware Guide
Ethereum Mining Rig - Hardware Guide
Tech With Tim
28 Pygame Tutorial #1 - Basic Movement and Key Presses
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
29 How to Install Pygame (Windows 8/10)
How to Install Pygame (Windows 8/10)
Tech With Tim
30 How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
31 How to Mine Ethereum 2018 - WORKING (Super-Easy)
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
32 Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
33 Pygame Tutorial #2 - Jumping and Boundaries
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
34 Pygame Tutorial #3 - Character Animation & Sprites
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
35 Pygame Tutorial #4 - Optimization & OOP
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
36 OBS Studio Tutorial - Best OBS Settings
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
37 Linear Search Algorithm - Python Example and Code
Linear Search Algorithm - Python Example and Code
Tech With Tim
38 Make Any Mic Sound AMAZING! (WITH OBS)
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
39 Binary Search Algorithm - Python Example & Code
Binary Search Algorithm - Python Example & Code
Tech With Tim
40 Pygame Tutorial #5 - Projectiles
Pygame Tutorial #5 - Projectiles
Tech With Tim
41 Pygame Game - Mini Golf
Pygame Game - Mini Golf
Tech With Tim
42 Pygame Tutorial - Projectile Motion (Part 1)
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
43 Pygame Tutorial - Projectile Motion (Part 2)
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
44 Pygame Tutorial #6 - Enemies
Pygame Tutorial #6 - Enemies
Tech With Tim
45 Pygame Tutorial #7 - Collision and Hit Boxes
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
46 Pygame Tutorial #8 - Scoring and Health Bars
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
47 Cloud Mining vs. Hardware Mining - 2018
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
48 How to Install Pygame on Mac OSX (Fast-Simple)
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
49 Pygame Tutorial #9 - Sound Effects, Music & More Collision
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
50 Pygame Tutorial #10 - Finishing Touches & Next Steps
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
51 How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
52 How to Create a Button in Pygame [CODE IN DESCRIPTION]
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
53 Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
54 Pygame Side-Scroller Tutorial #2 - Random Object Generation
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
55 Pygame Side-Scroller Tutorial #3 - Collision
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
56 Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
57 How to Create A Message Box in Python - Tkinter
How to Create A Message Box in Python - Tkinter
Tech With Tim
58 Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
59 How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
60 Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim

This video tutorial teaches how to create a server using Python sockets, handling multiple connections and storing/sending information. It covers setting up a socket, binding the server and port, and handling incoming connections using threading. By following this tutorial, viewers can learn how to create a basic server-client architecture using Python.

Key Takeaways
  1. Create a new file for the server called server.py
  2. Import necessary modules, including sockets, threading, and OS
  3. Define a server and a port, using port 5555 for the server
  4. Set up a socket using AF_INET and SOCK_STREAM types
  5. Bind the server and port to the socket using try and accept
  6. Listen for connections using s.listen()
  7. Accept incoming connections using s.accept()
  8. Start a new thread for each client connection
  9. Receive data from the client using a try-except block and the 'recv' method
  10. Handle client connections in a while loop
💡 Using threading allows the server to handle multiple connections concurrently, improving the overall performance and responsiveness of the server.

Related AI Lessons

I Asked ChatGPT to Fix My Life. It Couldn’t — Until I Changed One Thing
Learn how to effectively use AI like ChatGPT to improve your life by changing your approach
Medium · AI
I Asked ChatGPT to Fix My Life. It Couldn’t — Until I Changed One Thing
Learn how to effectively use ChatGPT to solve personal problems by changing your approach
Medium · ChatGPT
Claude Sonnet 5 Is Here: Why It Might Replace Your Opus Subscription
Learn about Claude Sonnet 5, a new AI model that offers near-flagship performance at a lower price, and its potential to replace Opus subscriptions
Medium · Programming
Claude AI vs ChatGPT: Which One Is Actually Better in 2026?
Compare Claude AI and ChatGPT based on real-world usage and benchmarking to determine which one is better in 2026
Medium · AI
Up next
5 Levels of AI Agents - From Simple LLM Calls to Multi-Agent Systems
Dave Ebbelaar (LLM Eng)
Watch →