Chat Server Using UDP Protocol

Aman Rathi
2 min readJan 25, 2021

You are already familiar with chat apps like WhatsApp, Telegram, Snapchat, etc. and they are using diff protocols to link clients with the servers, but here we gonna create our own chat server using the UDP protocol and also check the difficulties while using UDP as a protocol.

UDP

UDP(User Datagram Protocol) is a standardized method for transferring data between two computers in a network. Compared to other protocols, UDP accomplishes this process in a simple fashion: it sends packets (units of data transmission) directly to a target computer, without establishing a connection first, indicating the order of said packets, or checking whether they arrived as intended.

Let’s write the code for Server as well as for client

SERVER

import socket      #module used for networking#AF_INET used for IPv4#SOCK_DGRAM used for UDP protocol
s = socket.socket(socket.AF_INET , socket.SOCK_DGRAM )
#binding ip and port
s.bind(("192.168.1.103",23))
#recieving data from client
while True:
print(s.recvfrom(1024))

CLIENT

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#sending data to server
while True:
m = input()
s.sendto(m.encode(),("192.168.1.103",23)) #sending data in byte form to the server
client and server pc

Here we can see that reciever in server capture a tuple containing message in byte form and the client ip, we can filter the msg by slicing the tuple, but here there is a challenge that we cannot recieve and send the msg at a time because we cannot run multiple function at a time. So here we use multi threading concept to run multiple functions so that we can send and recieve messges at a time. So, lets customize the code

import socket
import threading
import os
s = socket.socket(socket.AF_INET , socket.SOCK_DGRAM )
s.bind(("192.168.1.106",23))#system ip
os.system("tput setaf 3")
print("=======Welcome to the chat page========")
os.system("tput setaf 2")
print("==============================================")
nm = input("Enter your name : ")
os.system("tput setaf 7")
def send():
while True:
ms = input()
sm = "{} : {}".format(nm,ms)
s.sendto(sm.encode() , ("192.168.1.104", 23) ) #server ip
def rec():
while True:
msg = s.recvfrom(1024)
os.system("tput setaf 5")
print("\t\t\t\t" + msg[0].decode() )
os.system("tput setaf 7")
x1 = threading.Thread( target = send )
x2 = threading.Thread( target = rec )
x1.start() #this will start the function at the same time
x2.start()

This code is same for both server and client we have to just change the ip’s

UDP is not so much reliable for chatting because it is a connectionless protocol, it doesn't care that client is active or not it will send the data continiously unlike tcp. UDP is used for live streaming video and games.

THANK YOU

--

--