Chat App using UDP and Multi threading in Python

Saurabh Suthar
4 min readApr 13, 2021

In this article, I’m going to explain how I made a simple chat app using UDP and multithreading.

Firstly, I’m creating the receiver and sender program without multithreading. But, the communication will be one sided if we use this approach that’s why I used the multithreaded approach later.

Socket, os and threading library is used to create the app in this tutorial.

What is the Socket?

Socket is the library that is used to form socket connection for internet communication.

Socket is the endpoint to communicate with the process over the network by using the combination of IP address and port number.

What is the threading?

Threading is the library that is used to achieve the multi-tasking while executing the process. Thread is the smallest unit of execution and uses context-switch to switch between the threads.

What is UDP?

UDP (User Datagram Protocol) is the protocol that is used to communicate the information without any acknowledgement either it’s received or not. It is mainly used in video streaming and where the acknowledgement is not necessary.

I’m using socket.SOCK_DGRAM as UDP protocol and socket.AF_INET as IP_v4 address family.

Let’s have a look into the code for the first approach:

Receiver’s code

socket.socket(afm, udp) is used to create socket and the socket object is used to bind the IP address and port number. Then, s.recvfrom(1024) is used to receive the message from the socket with the maximum size of 1024 bytes.

Sender’s code

Same socket object is used here and object.sendto() is used to send the message in binary format and with the socket address of the receiver.

Here, you can use the message.encode() while sending the message with the binary format.

This is the message received by the receiver’s side. It listens the socket while something is received or not. As soon as the message is received, it gets completed and disconnect itself.

Drawback of the above approach, one sided communication like simplex communcation.

Chat app using multi-threading

This application uses the same concept with a little twist like continuous duplex communication using multi threading and while loop.

Receiver’s and Sender’s IP address is taken as input for creating a socket.

recv() function is used to listen the socket for any message continuously and when the quit keyword is received, the chat’ll be ended on both the sides.

send() function is used to send the message over the network communication and quit is used to end the conversation.

Send and receive threads are created to communicate in the duplex parallely.

Below are some screenshots of chat program.

--

--