Simple Chat Room using Python (2021)
In This article, we are going to set up a simple chat room using Python. Here we are going to use some basic concepts of Socket programming working on UDP and TCP protocol.
Table of content
- Socket Programming Intro
- Room setup using UDP
- Room setup using TCP
- Final Voice
A Socket programming is a way of connecting two or more nodes on a layer. Here communication is set between server and clients(one or more). Where socket can be thought of as endpoints of the communication channel which is a combination of IP and port number. Now, the socket connection over the same port number can connect.
We actually don’t need much knowledge as per our project now. I will explain all the required details at the time of programming.
The User Datagram Protocol, or UDP, is a communication protocol used across the Internet for especially time-sensitive transmissions such as video playback or DNS lookups. It speeds up communications by not formally establishing a connection before data is transferred. This allows data to be transferred very quickly, but it can also cause packets to become lost in transit.
Transmission Control Protocol, or TCP, is also a communication protocol used to send an important piece of information. Data packets are much more secured in this protocol. It first establishes a connection between server and client and then sends the data packets. It is slower than UPD protocol.
A thread is a sub-process that runs a set of commands in programming. Every time when we run an application some threads are assigned to that application which helps to complete the task. In our python programming, Generally, a single thread is assigned to the program but in this task, we required multi-threading concepts. Why?
In our chat room, we will listen to other clients, and same time we should be able to send the data as well. To keep both the service on we have to use 2 threads.
Room setup using UDP
In this project, we are going to set up a UDP connection between two nodes. For this setup, We have to require two different OS. Therefore I am using VirtualBox. On top of this VirtualBox, I have two different OS running.
Download full code from ===> GitHub
Without wasting time let’s just dive into the coding:
Server Code in UDP
import socket # ==== udp protocol ===== myp = socket.SOCK_DGRAM # ===== net address family name: ipv4 ===== afn = socket.AF_INET s = socket.socket(afn,myp) # =========== Server ip ============ ip = "192.168.43.57" # =========== Port ============== port = 1234 # ======== To bind the IP & Port ========== s.bind((ip,port)) while True: # ====== To receive the message ====== x = s.recvfrom(1024) # ====== IP of client ====== ip = x # ====== Message of client ====== res=x.decode() # ==== To close the program ==== if(res=='exit'): print() print('==== Exiting the program ====') break; # ====== print the message ====== else: print(ip+ ': ' + res)
Client Code in UDP
import socket # ====== For UDP Protocol ====== s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # === ip of your server VM === ip = "192.168.43.57" # === port === port = 1234 # === To connect with the ip and port === s.connect((ip,port)) print("========= Connection is Established =========") print() while True: # === To take the input === msg = input("Enter the message('exit' to close the program): ") # === To convert it into byte === msg = str.encode(msg) # === message sending === s.send(msg) # === Exiting Case === if msg.decode() == "exit": print() print("============ Connection is closed ==============") break;
In this above setup, we can only send the message from our client system to the server system. It is super fast but there may be a case where packets can be lost.
To overcome this we have a TCP protocol that first creates a connection and then we will be able to send the message. In a simple manner, first, a chat room will be created and after that only we will send our message.
Room set up using TCP
In the previous section, we have created a UDP server in which we are able to send messages from the client only and packet loss also may occur. Now, in TCP protocol, we are going to send and receive messages from both the end using multi-threading concept.
Without wasting much of our time let’s jump right into the code.
Server code in TCP
# ======= Used Libraries ======== import socket import threading import os # ===== For TCP Protocol ====== s = socket.socket() # ====== Server IP & Port ====== ip = "192.168.43.57" port=1234 # ====== To bind the packet ====== s.bind((ip,port)) # ====== To Listen on the given Port ====== s.listen() # ====== Get details about Client ====== c, addr = s.accept() cip=addr print("==== Connection is Established ====") # ====== Receive Function ====== def recv(): # ===== For infinitely running loop ====== while True: # ====== To receive the message ====== msg = c.recv(1024) # ====== To decode the encoded message ====== msg = msg.decode() # ====== To add the exiting condition ====== if(msg=="exit"): print("==== Exiting from the program ====") os._exit(1) # ====== To print the client's message ====== print(cip+": "+ msg) # ====== Send Function ====== def send(): # ===== For infinitely running loop ====== while True: # ====== To input the message ====== msg = input().encode() # ====== To send the message ====== c.send(msg) # ====== Exit condition ======= if msg.decode()=="exit": print("==== Exiting from the program ====") os._exit(1) # ====== Threads ======= t1 = threading.Thread(target=recv) t2 = threading.Thread(target=send) # ====== To start the threads ====== t1.start() t2.start()
Client code in TCP
# ====== Used Libraries ====== import socket import threading import os # ====== For TCP Protocol ====== s = socket.socket() # ====== Server IP & Port ====== sip = "192.168.43.57" sport=1234 # ====== To connect the program ====== s.connect((sip,sport)) print("==== Connection is Established ====") print("==== Type your message('exit' to close the program)") # ===== Send Function ====== def send(): # ===== For infinitely running loop ====== while True: # ====== To input the message ====== msg = input().encode() # ====== To send the message ====== s.send(msg) # ====== Exiting condition ====== if msg.decode()=="exit": print("==== Exiting from the program ====") os._exit(1) # ====== Receive Function ====== def recv(): # ===== For infinitely running loop ====== while True: # ====== To receive the message ====== msg = s.recv(1024) # ====== To decode the encoded message ====== msg = msg.decode() # ====== Exiting condition ====== if(msg=="exit"): print("==== Exiting from the program ====") os._exit(1) # ====== To print the server's message ====== print(sip+": "+ msg) # ====== Threads ======= t1 = threading.Thread(target=send) t2 = threading.Thread(target=recv) # ====== To start the threads ====== t1.start() t2.start()
Now, we are ready to launch our chat room.
Firstly run the server file and then the client file. You will get an output of “Connection is Established” or something and there you are ready to send the message from both the end.
NOTE: It is compulsory that both the Operating Systems must be in the same network. (You can use your mobile hotspot to connect with both the os).
You can also use one of your OS as your mobile phone.
Download the complete code from ==> GitHub
In this amazing practical we have learned the basics of socket programming. In which we have created a simple chat room using python. Firstly, we have created a simple chat server using UDP protocol. And after that using the multi-threading concept we used TCP protocol to create our final chat room.
In this chat room, we can communicate from both the end. You can improve this chat program by adding some frontend techniques.
Comment your thoughts about this project and Don’t forget to subscribe to our newsletter for future updates.
You can now Subscribe BrighterBees on Youtube.