Chat Server using UDP Protocol

Juzer Patanwala
3 min readMar 25, 2021

In this guide,we will create our own chat servers and establish a network to trasnfer data using Socket Programming.Both the server and client machine will have both Sender as well as Receiver Programs.We will use the multi-threading concept to send and receive data parallelly between the sender and receiver programs on both sides.

What is Socket Programming?

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. Server forms the listener socket while client reaches out to the server.
They are the real backbones behind web browsing. In simpler terms there is a server and a client.

Now that we know what is socket programming,let’s start off with our hands-on part.

Import the socket library

Socket programming is started by importing the socket library and making a simple socket.

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_DGRAM. AF_INET refers to the address family ipv4. The SOCK_DGRAM means the connection will be using UDP protocol.

Bind the socket to a port and ip

The socket class has a bind() method which binds it to a specific ip and port so that it can listen to incoming requests on that ip and port.

ip = "192.168.1.4"  
port = 1234
s.bind((ip,port))

Create the function for receiving messages on the binded port

This function will work as the receiver.It will retrieve the packets received on the port 1234 and print out the payload(data) from the packet received through network.Here,I have used the colored and colorama libraries to print the received message in some different colors.

from termcolor import colored
from colorama import init
#Receiver function
def recv() :
while True :
x = s.recvfrom(1024)
print(colored(text ="\t\t\t\t\t\t"+ x[1][0] + " : " + x[0].decode()+ "\n", color='cyan', on_color='on_grey',attrs= ['blink']))

os.system('tput setaf 7')
if x[0].decode() == "Bye" :
exit()

Here,the message received,stored in the variable x,is a tuple and the message is retrieved from x[0].The data when sent across a network is generally in bytes and to convert it into a string we have to use the decode( ) function.

Also,we have used a while loop so that the messages are received untill the message “Bye” gets received.

Create the function for sending messages to another port and ip

This function will work as the sender.It will send packets using UDP protocol to a specific port and ip address.

send_ip = input("Enter the IP of person you want to chat with : ")
send_port = 1084
#Sender function
def send() :
while True :
msg = input("\n").encode()
s.sendto(msg,(send_ip,send_port))

The sendto( ) function sends the message to the IP address inputted by the user and the port number specified.

Now,in any programming language,by default only statement or function can be executed at a time.So,by default we can run either the send function or the receive function at a time.But,in a chat server we have to run both the sender and receiver functions parallelly.To achieve this,we can use the concept of Multi-Threading in Python.

Use Multi-Threading to both send and receive messages simultaneously

Multi-Threading is a concept through which we can run multiple functions parallelly in Python.These functions which we run in parallel are called Threads.

#Creates a thread for running the receiver function
receive = threading.Thread(target = recv)
#Creates a thread for running the sender function
send = threading.Thread(target = send )
#Starts the sender function thread
send.start()
#Starts the sender function thread
receive.start()

The entire program :

import socket
import threading
import helper
import os
from termcolor import colored
from colorama import init
init(autoreset=True)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip = "192.168.1.4"
port = 1234
s.bind((ip,port))
print("------Welcome to UDP Chat Application--------")
send_ip = input("Enter the IP of person you want to chat with : ")
send_port = 1084
def recv() :
while True :
x = s.recvfrom(1024)
print(colored(text ="\t\t\t\t\t\t"+ x[1][0] + " : " + x[0].decode()+ "\n", color='cyan', on_color='on_grey',attrs= ['blink']))
os.system('tput setaf 7')
if x[0].decode() == "Bye" :
exit()
def send() :
while True :
msg = input("\n").encode()
s.sendto(msg,(send_ip,send_port))
recieve = threading.Thread(target = recv)
sen = threading.Thread(target = send )
sen.start()
recieve.start()

We can run the same program on the two systems we want to chat with.

Thank You!!

--

--

Juzer Patanwala

Cloud Engineer @ Searce Inc || Technical Content Writer || Technology and Automation Enthusiast