Simple ChatApp using UDP in python

Dhiraj Kumar
2 min readJan 9, 2021

In this blog chatApp is created using UDP protocol in python language . In this chatApp server and client both are working parallel .

For creating ChatApp between two OS , it is necessary to transfer data between two OS. For transfer data protocol is used ,there are two types of protocol are available .

=> tcp(transfer control protocol)and udp(user datagram protocol) . tcp is connection oriented protocol whereas udp is connectionless protocol.

=>When tcp is used for transfer data , one connection is created between client and server and when client send data to server then one acknowledgement is sent to client from server side.

=>When udp is used for transfer data, no one connection is created between client and server only data is sent to server by using IP address and port number. And there is no any acknowledgement is sent to client from server side.

Requirements in this task:

I have used two OS with python installed , one is windows and other is linux.

Socket module

threading module

Python code used in windows OS:

import socket
import threading
def server():
s= socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip="192.168.43.222"
port=1235
s.bind((ip,port))
while True:
mrecv=s.recvfrom(1024)
text=mrecv[0].decode()
print("Massage Recieved: ",text)

def client():
s= socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
msend=input()
print("Massage Sent: ",msend)
s.sendto(msend.encode(),("192.168.43.109",1234))



t1=threading.Thread( target=client )
t2=threading.Thread( target=server)
t1.start()
t2.start()

Python code used in linux OS :

import socket
import threading
def server():
s= socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip="192.168.43.109"
port=1234
s.bind((ip,port))
while True:
mrecv=s.recvfrom(1024)
text=mrecv[0].decode()
print("Massage Recieved: ",text)

def client():
s= socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
msend=input()
print("Massage Sent: ",msend)
s.sendto(msend.encode(),("192.168.43.222",1235))



t1=threading.Thread( target=server )
t2=threading.Thread( target=client)
t1.start()
t2.start()

In socket module there is a socket() function , in which socket.AF_INET parameter is used which decides that IPv4 address type is used for IP address. And socket.SOCK_DGRAM parameter is used which decides that udp protocol is used for transffer data

When data is sent from client side then data should be in encoded string is enconded using encode() function . And encoded data is converted in string using decode() function.

For use server and client programme parallel using udp protocol , multi threading concept is used . For multi threading threading module is used .

--

--

Dhiraj Kumar

Expertise on Cloud Computing who has helped many startups to reduce cloud cost upto 40% based on business need. Focused to optimize development process.