Socket Chatroom server - Creating chat application with sockets in Python
Key Takeaways
The video demonstrates creating a chat application with sockets in Python, handling multiple connections, and using select for operating system level IO capabilities. It covers setting socket options, binding the socket to a specific IP and Port, and handling message length or disconnection.
Full Transcript
what's going on everybody and welcome to another sockets tutorial video in this video we're going to be kind of trying to put everything together and maybe learn a couple new Concepts and what we'd like to do is create a chat application so we're going to need a server and then a client which is pretty common to what we've seen so far but the difference that we're going to have here is our server is going to handle many clients and when the client connects basically it's a chat room right so the client needs to be able to send messages to the server and then the server needs to distribute all of the messages to everyone okay and then we also have like little stuff like usernames and stuff like that but for the most part the biggest thing that is going to be different here is this kind of uh broadcast or distribution uh that we've never done and then also just just simply even even that or also just handling multiple connections so that would probably be the title if I had to pick one that wasn't like chat app or whatever is just just handling multiple connections on the server side so anyway uh with that let's go ahead and uh zoom in imagine if I did an entire tutorial uh that size I'd have to move my face anyway uh import socket uh because we're going to use that and then the way that we're going to manage many of connections of these connections is going to be with uh what's called select which gives us operating system level IO capabilities so like with sockets in mind so on Windows it would be different than say on Linux and because of that python has select that allows us to utilize that without needing to get into the details so that this code will run the same whether you're on Mac Linux or Windows so okay then what we're going to do is we're going to have a couple of constants here so header length will make that equal to 10 and then we're going to set IP okay IP and in this case we'll do 1271 and then we'll say Port uh 12 through 4 okay now we're going to go ahead and make the socket so server socket will be socket. socket and the type is socket. AF uh inet someone told me uh actually probably multiple people told me but AF stands for address family and I believe inet is just like internet anyway um the next thing is this is a socket. sock whoops sock stream stream there we go we can type today uh let me zoom out I just want to zoom out enough to where everything's on screen but then hopefully not too too small so that should do okay so now uh what we want want to do is uh we want to stop so if you you've maybe hit it playing with sockets and I think we hit it in some of the tutorials where I had to keep ticking up the port number so we could rerun things and it wouldn't say addresses in use one option you have to overcome that is just server socket. set sock op and then socket. socket option levore socket so if I recall right um you've got like three options here and it's like the thing you want to set and then what you want to set of that thing and then you set the thing okay so we're going to set this um what do we going to set that like what attribute of that are we going to set it's going to be socket doso socket option uh reuse address and we want to set that to one which is true so that's a little funky we're not really used to setting things that way in Python anyways um and I could be totally wrong what this is going to do is allow us to reconnect and I believe that's what we're doing so the next thing is server socket. bind and then we just bind as usual the tupal of Ip and Port um actually I guess you wouldn't have a space there it wants a space space there that's hard cuz it would be it's a tuple inside of a parameter at least it thinks I should have a space I'll have a space uh server uncore socket whoops uh server socket. listen and then we're ready to actually start the code so really everything up to this point other than I suppose this here uh is stuff that should be pretty familiar with you or to you and anyway it's been a few days since I've done a tutorial video um getting a little rusty uh I ended up having a cold so yeah cool fun now it's a good time um so now we're going to start doing the actual server stuff so the first thing we need to do if we're going to manage a you know a uh a list of clients is to actually have the list of clients and really we don't have clients we have sockets so we're going to say sockets list um and that could be empty although we actually already have one and that's the server socket so just paste in server socket there now later as clients connect uh we'll also have the server um we'll have the clients in this list rather um but for now it's just server socket that's the only one we're aware of right now now later we probably want to think of these clients and at least report these clients to the other clients with something better than their you know their socket information so probably something other than their IP and port or you know that kind of thing so what we're going to say instead is we're going to have a client uh a client's dictionary where these client socket will be the key and then the user data uh can be the value so um so we got client's list okay so now what we need to do is basically the main thing that um the server is going to do and that is is simply receive messages so we're going to create some space and let's say Define receive uncore message and the parameter here will be from any client socket now what we want to do is try um and then accept I'm going to just write pass here we'll fill that in in a moment so what we want to attempt to do is first of all we want to receive the message header and that's going to be client socket. receive and then we want to receive whatever um the header length is uh and that will give us the header and then uh if if not Len message header so basically we didn't get a thing so if we didn't get any uh data the client closed the connection um so so we just need to handle for this so we're just going to to say return false otherwise what we want to say is uh message length equals whatever the int value of message header. decode utf8 um and that's it um just for proper Clarity we could throw the strip in there so I think I talked about this as well uh at least in Python you don't have to strip there and it feels really weird that you can convert like a number with some spaces to like a string of a number with spaces to a number uh so you might want to just toss in the strip there just just so you understand because I don't think You' I think that like python would be one of the few languages you're going to get away with that on so anyway you can throw the strip in there um you don't actually need it in Python though at Le at least the last time we didn't need it we can we can test that later or you can try to test that later but anyway so now uh we're going to return a dictionary where the value is so for header we're just going to say the message header and then we're going to pass uh data and data will be client socket socket. receive and then whatever the message length is so in this case we're just going to receive exactly however long that is and I guess you know you would just hope that someone doesn't send some gigantic message but um it's a chat room so later you could probably just handle for length or maybe we will I don't know um but yeah you just would have to think about that as far as the size but hopefully no one's going to send a message that's like you know 50 megabytes or something uh anyway continuing on uh okay so we return that now uh if we hit this other exception uh there's I mean pretty much the only way you would hit this is if someone like broke their script or something like so if the client just like closed really aggressively um so in this case let's just return oh and I already noticed I return capital F false and let's fix this one as well done okay so now we're able to receive messages now what we want to do is receive messages and um really there's only going to be like two types of messages there's going to be on an initial connection and then otherwise this is just a chat message so um let's do come down here and we'll say while true and we're going to say red sockets um thing we don't care about and then exception sockets which we sort of care about but anyway select we really just care about the first one but anyway that's okay select do select uh sockets unor list we'll just make this an empty list and then uh sockets list again so what these are is so select. select takes in three parameters you've got a read list so the things that you want to read in the write list so this would be sockets we're going to read sockets we're going to write and then this would be sockets that we might error on and so uh and then you can like you can decide what you want to do with these errors but mainly our our main concern is this read list so this is these are the ones that we actually want to read in and get data from so coming down to the read sockets this is where the bulk of our like logic will be handled so what we're going to say is for notified socket in red sockets sockets um if notified notified socket is the server socket this means someone just connected um and we need to accept this connection and also just like handle for it so the way that we're going to do that is uh client socket client um address is equal to server socket. except so we'll bring in that connection then we're going to say the user is equal to receive unor message uh client socket so uh recall that would be here so we're going to receive that message client socket we get the header data and then we get data data okay so the user we're going to say is equal to client we're I'm probably making lots of typos here that we're going to only find out in the next video uh when we do the uh the other side of this the client side then we'll run it and then likely debug a lot of things that'll be fun so okay user receive message and then if user is uh false someone just disconnected so we'll just say continue here uh otherwise sockets uh uncore list. aend uh we'll pend that client socket to that list and then we're going to say clients client socket equals user so recall user is this dictionary of data here so you've got the header and then data uh for that user so that's the current information we have on this client socket basically and then um what we want to say is just we can just gives some simple information so we'll just say accepted new connection from port or IP colon Port uh and then we'll say username this so um in this case I'm going to make this an F string and I'm going to say client address zero client uncore address one let me just zoom out so everybody can see what's going on here and then this would be user data user data. decode oops utf8 um this may be one of the first times I've done embedding inside of quotes I'm not sure we're going to get away with that we may end up having to format it but I'm going to stick with that for now uh and we'll see it'll be fun so uh okay let me zoom out so anybody can see that we're going to have to to zoom back in so we can uh see again but otherwise cool so now what we want to say is so that was like if someone just re like just connected now uh otherwise what do we want to do so we want to actually handle for this so it's a message equals receive message again uh notified socket so um message equals receive message notified socket and then if message is false for whatever reason we're going to say uh closed connection from and we will say clients notified socket data do decode do this I utf8 so the other thing we could do is like set this as a value and then pass that through there so we can keep using F strings I'll be curious to see if this works if you can like embed that way I don't think I've ever actually needed to do that so okay now if message is false great and then sockets uncore list. remove notified socket so we'll get take that out of the list and then we also want to Dell clients notified socket and then uh we'll continue so that's if the message is false otherwise capitalize that F again I can't wait to see how many errors I've made so far uh now we're going to say uh user equals clients notified socket cuz we already have this client now now we're just going to print um um an F string Reed message from and we'll say user data. decode and we'll decode to utf8 and um and then we'll put in the message so we'll say colon and then the message itself is message data. Deco decode oops get back here UTF 8 okay so we see the message now what we need to do is share this message with everybody so I'm going to say for client socket in clients what do we want to do uh if client socket is not our notified socket so we obviously don't want to send this right back to the sender so we don't need to like repeat that send um so if that's not the case uh client socket. send user header plus user data plus message header plus our message data so we send in all that information so both the username with the Header information and then after that we send the message uh with its Header information as well this way on the client side we can display both username message username message so we'll just know that okay we're going to accept kind of like two two groups of things the usern name data and then the actual message itself okay now um for notified socket in red sockets the other thing we can say too is for uh notified socket in exception sockets again again we can kind of just ignore these um but we'll go ahead and uh just handle them since we can get this information anyway so we'll just say sockets list. remove notified socket and then Dell clients notified socket okay save that and I do declare I think we we've completed our server so what are you angry about two blank lines after a function definition duh everybody knows that save that uh I'm just looking for any uh syntax issues uh I don't think my pep8 thing doesn't seem to understand how F strings work so I'm pretty sure that's all this is but uh this could totally be an issue uh we'll figure that out when we actually go to run everything and in fact we could actually we could just run it real quick right now uh we don't have to run um we we're not going to connect anything to it but we could at least um I forget what python okay that's good enough uh python server.py no we actually do have a syntax error here uh received message this is what you're saying is a syntax error really received message [Music] from maybe because we actually haven't hit this pi- 37 server.py no so received message so it's angry about this one what have I done this is like these are are a little uh compacted so let's just say uh user username equals let's just grab cut paste oh it's the double quotes that I used here let me fix that real quick save that let me run that again okay it looks like our server actually runs we won't know so uh we don't actually know if this is going to wind up erroring on us or not doing what we hoped until we actually run it and connect a client to it but at least up to this point the code runs so that's good that's good okay so in the next tutorial we will work on our uh client code quick shout out to my recent uh channel members slong time members papasani Mohan I'm going to call you Mohan for short uh 7 months Gan enzor 10 days new uh new member thank you very much for your support jatin nandwani also a new member fidget also a new member Jackson Warren two months and Michael Park 13 days also a new member thank you all very much for your support you guys are all awesome okay I will see everybody in the next tutorial where we write our client code as well as debug the like at least least 100 errors I probably wrote so far it's going to be a great time I'll see you guys there
Original Description
We've made it through the basics of working with sockets, and now we're ready to try to actually build something with them, so, in this sockets with Python tutorial, we're going to build a console-based chat app.
Text-based tutorials and sample code: https://pythonprogramming.net/server-chatroom-sockets-tutorial-python-3/
Channel membership: https://www.youtube.com/channel/UCfzlCWGWYyIQ0aLC5w48gBQ/join
Discord: https://discord.gg/sentdex
Support the content: https://pythonprogramming.net/support-donate/
Twitter: https://twitter.com/sentdex
Facebook: https://www.facebook.com/pythonprogramming.net/
Twitch: https://www.twitch.tv/sentdex
G+: https://plus.google.com/+sentdex
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from sentdex · sentdex · 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
Matplotlib Python Tutorial Part 1: Basics and your first Graph!
sentdex
Python Encryption Tutorial with PyCrypto
sentdex
Python's Logging Function
sentdex
wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
sentdex
wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
sentdex
wxPython Programming Tutorial 3: Menu Bar and Menu Button
sentdex
wxPython Programming Tutorial 4: Panels
sentdex
wxPython Programming Tutorial 5: User Input Saved To Variables
sentdex
wxPython Programming Tutorial 6: Multiple Choice Input
sentdex
wxPython Programming Tutorial 7: Adding Static Text and Colors
sentdex
wxPython Programming Tutorial 8: Custom Button Images
sentdex
wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
sentdex
Basic PHP Tutorial 13: Multi-dimensional Array
sentdex
Basic PHP Tutorial 15: Functions and Global Variables
sentdex
Basic PHP Tutorial 12: Associative Array
sentdex
Basic PHP Tutorial 14: Foreach loop
sentdex
Basic PHP Tutorial 16: Include and Require
sentdex
Basic PHP Tutorial 7: Assignment, comparison and Logical operators
sentdex
Basic PHP Tutorial 4: Variables and Comments
sentdex
Basic PHP Tutorial 11: Arrays part 1, basic array
sentdex
Basic PHP Tutorial 6: If else and else if conditionals cont'd
sentdex
Basic PHP Tutorial 1: Intro to PHP
sentdex
Basic PHP Tutorial 3: HTML with PHP
sentdex
Basic PHP Tutorial 9: While Loop
sentdex
Basic PHP Tutorial 10: Switch Statement
sentdex
Basic PHP Tutorial 2: Print and Echo
sentdex
Basic PHP Tutorial 5: If else and else if conditional statements
sentdex
Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
sentdex
Basic PHP Tutorial 17: User Input Form Example / String Manipulation
sentdex
Basic PHP Tutorial 18: HTML Entities and forms cont'd
sentdex
Basic PHP Tutorial 19: Finding words in strings
sentdex
Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
sentdex
Basic PHP Programming Tutorial 22: Hashing part 2: salting
sentdex
Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
sentdex
Basic PHP Programming Tutorial 21: MD5 Hashing For Security
sentdex
Basic PHP Programming Tutorial 24: String similarity
sentdex
Basic PHP Programming Tutorial 25: Time and Time stamps
sentdex
Basic PHP Programming Tutorial 26: Die and Exit
sentdex
Basic PHP Programming Tutorial 27: MySQL Databases Part 1
sentdex
Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
sentdex
Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
sentdex
Basic PHP Programming Tutorial 30: MySQL database in Use
sentdex
Django Tutorial Web Development with Python Part 1: Installing Django
sentdex
Python Tutorial: File Deletion and Folder Deletion / directory deletion
sentdex
Python Tutorial: How to Rename Files and Move Files with Python
sentdex
3D Graphs in Matplotlib for Python: Basic 3D Line
sentdex
3D Plotting in Matplotlib for Python: 3D Scatter Plot
sentdex
3D Charts in Matplotlib for Python: Multiple datasets scatter plot
sentdex
Sikuli Tutorial 1: Visually programming in python!
sentdex
Sikuli Tutorial 2: Program visually in python!
sentdex
Sikuli Tutorial 3: Program visually in python!
sentdex
3D Bar Charts in Python and Matplotlib
sentdex
3D Plane wire frame Graph Chart in Python
sentdex
Raspberry Pi Part 1 Introduction
sentdex
Raspberry Pi Part 8: First Download and Update! (Firmware)
sentdex
Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
sentdex
Raspberry Pi Part 11: Remote Desktop
sentdex
Twitter Analysis: How to rank a user's influence
sentdex
GPIO Tutorial for Pi Part 2 - Programming the GPIO
sentdex
GPIO Tutorial for Raspberry Pi Part 1 - Setting up
sentdex
More on: Tool Use & Function Calling
View skill →Related Reads
📰
📰
📰
📰
A Gen X entrepreneur closing their laptop at the end of a productive, shortened workday, ready to…
Medium · AI
Earning Technical Certifications in 5 Steps with AI Tools
Dev.to AI
10 AI Tools That Can Save You Hours Every Week
Medium · AI
I Built Python Tools for Small Problems — They Ended Up Saving Me Hours
Medium · Programming
🎓
Tutor Explanation
DeepCamp AI