Chat Server from UDP protocol

Abhishek Arora
2 min readJan 25, 2021

So basically Chat server is a server which is used for communication between 2 or more hosts. Here we create a python program which will act as both chat server and client and help us to chat from System A to System B.

The protocol we used here is UDP which is connectionless protocol and is also not reliable. TCP protocol is Connection Oriented as well as Reliable.

UDP has its own benefits such as

  • Fast
  • Low Latency
  • More Control
  • No connection creation needed

UDP can be used for data which can tolerate loss that means that the data transmitted over UDP protocol can be lost

The concepts needed to implement this are:

  • Socket Programming
  • Multi-Threading

Multi threading is done in order to send and receive the messages simultaneously otherwise by default UDP waits for reply from another side and then can proceed to send message

  • Create Socket by binding IP and Port
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = “172.31.19.93”
port = 32768
s.bind((ip, port))

AF_INET is is to indicate that ipv4 is used and SOCK_DGRAM is used for UDP

  • Code For sending message
message = input(“Enter the message: “)
s.sendto(message.encode(), (recveiverIP, recveiverPort))

The message needs to be encoded before sending and also the message needs to be decoded before receiving message

  • Code for receiving message
data = s.recvfrom(1024)
data = data[0].decode()
print(f’\nReceived message: {data}’)

There is 1024 in recvfrom() function as this indicates the bytes to receive. recvfrom is used to take input from a server program

Multi Threading is enabled for running multiple process and in this case we are running two functions simultaneously that is to send and receive message

send = threading.Thread(target=sMessages)
receive = threading.Thread(target=rMessages)

Also we need to start these threads using

receive.start()
send.start()

A video of complete demonstration is below

--

--