✍TO CREATE A CHAT APPLICATION USING THE CONCEPT OF SOCKET PROGRAMMING AND MULTI-THREADING IN PYTHON :

Priya Soni
8 min readApr 26, 2021

HELLO EVERYONE ✌✌,

This article will help you to learn, How we can Create a Chat application using the concept of Socket Programming and Multi-Threading in Python.

Next we gonna see How to write our python code from the scratch for creating a chat application in python using UDP protocol.

✨ This particular demonstration will also helps us to learn concept of UDP protocol which is also known as connection less protocol.

✍ TASK DESCRIPTIONS :

🔅 Create your own Chat Servers, and establish a network to transfer data using Socket Programing by creating both Server and Clinet machine as Sender and Receiver both. Do this program using UDP data transfer protocol.

🔅 Use multi-threading concept to get and receive data parallelly from both the Server Sides. Observe the challenges that you face to achieve this using UDP.

👉But before starting let’s understand some basic terms.

✍WHAT IS UDP PROTOCOL ?

User Datagram Protocol (UDP) is a Transport Layer protocol. UDP is a part of Internet Protocol suite, referred as UDP/IP suite. Unlike TCP, it is unreliable and connectionless protocol. So, there is no need to establish connection prior to data transfer.

UDP PROTOCOL

✍APPLICATION OF UDP :

Following implementations uses UDP as a transport layer protocol:

  • NTP (Network Time Protocol)
  • DNS (Domain Name Service)
  • BOOTP, DHCP.
  • NNP (Network News Protocol)
  • Quote of the day protocol
  • TFTP, RTSP, RIP.

NOTE : In networking world rules also known as protocol.

✍UDP COMMUNICATION :

UDP COMMUNICATION

✍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.

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 UDP is connection less protocol.

Now we can connect to a server using this socket.

NOTE : The combination of ip address and port number is known as socket and the unique number is also known as port number.

✍WHAT IS Recvfrom FUNCTION IN SOCKET PROGRAMMING ?

The recvfrom() function shall receive a message from a connection-mode or connectionless-mode socket. It is normally used with connectionless-mode sockets because it permits the application to retrieve the source address of received data.

✍WHAT IS THREAD ?

In computing, a process is an instance of a computer program that is being executed. A thread is a single sequential flow of control within a program.

Consider the diagram below in which a process contains two active threads:

MULTI-THREADING IN PYTHON

In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other code. For simplicity, you can assume that a thread is simply a subset of a process!

✍WHAT IS MULTI-THREADING IN PYTHON ?

Multithreading is defined as the ability of a processor to execute multiple threads concurrently.

Consider the diagram below to understand the relation between process and its thread:

Consider the diagram below to understand how multiple threads exist in memory:

Before doing any practical implementations It’s a good practice to create one seperate directory to store all the files.

This directory is also known as our Workspace. In my system I created one workspace called “TASK17”.

I am putting everything in this workspace and at the end of this article I will provide the GitHub link, from where you can download this workspace and also use it.

In this task I will be using 2 different types of OS, one will be Windows and another will be Linux.

In socket programming, A server 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.

socket_family: Defines the family of protocols used as the transport mechanism. It can have either of the two values.

  • Either AF_UNIX, or
  • AF_INET (IP version 4 or IPv4).

socket_type: Defines the types of communication between the two end-points. It can have the following values.

  • SOCK_STREAM (for connection-oriented protocols, e.g., TCP), or
  • SOCK_DGRAM (for connectionless protocols e.g. UDP).

protocol: We typically leave this field or set this field to zero.

👉SO, WE HAVE TO WRITE A PYTHON PROGRAM IN WINDOWS FOR CHAT APPLICATION :

# cd TASK17

# notepad chat_windows.py

👉NEXT :

✍CODE :

import socket as soc
import threading as thread
import os
import pyfiglet
os.system("cls")
os.system("color 6")
title = pyfiglet.figlet_format("\t ! WELCOME TO MY UDP CHAT APP FROM WINDOWS ! \n")
print( title)
print(" \n ##################################################################### \n")
print("\t\t SO FRIEND LET'S START OUR CHATTING \n")
print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ \n")
your_ip = input("ENTER THE YOUR IP ADDRESS HERE : ")
print("\n")
your_port = int(input("ENTER THE YOUR PORT NUMBER HERE : "))
print("\n")
frd_ip = input("ENTER THE FRIEND IP ADDRESS HERE : ")
print("\n")
frd_port = int(input("ENTER THE FRIEND PORT NUMBER HERE : "))
print("\n")
# TO CREATE A SOCKET AND BIND THE IP AND PORT NUMBER :skt1 = soc.socket(soc.AF_INET, soc.SOCK_DGRAM)
skt1.bind((your_ip, your_port))
# WE CAN USE THIS FUNCTION TO RECEIVING AND PRINTING THE MESSAGE :def recieve_msg():
while True:
os.system("color 5")
msgRcv = skt1.recvfrom(1024)
if msgRcv[0].decode() == "quit" or msgRcv[0].decode() == "bye bye" or msgRcv[0].decode() == "exit":
print("NOW YOUR FRIEND GOES OFFLINE!")
os._exit(1)
print("\n\t\t\t YOUR FRIEND'S MSG --->" + msgRcv[0].decode())
# WE CAN USE THIS FUNCTION TO SENDING THE MESSAGE :def send_msg():
while True:
data = input().encode()
msgSent = skt1.sendto(data, (frd_ip, frd_port))
if data.decode() == "quit" or data.decode() == "bye bye" or data.decode() == "exit":
os._exit(1)
# WE CAN USE THIS THREAD FOR SENDING THE MESSAGE FUNCTION :t1= thread.Thread(target=send_msg)# WE CAN USE THIS THREAD FOR RECIEVING THE MESSAGE FUNCTION :t2 = thread.Thread(target=recieve_msg)# WE CAN USE THIS FUNCTION TO STARTING OUR THREADS :
t1.start()
t2.start()

👉SO, WE HAVE TO WRITE A PYTHON PROGRAM IN LINUX FOR CHAT APPLICATION :

# cd TASK17# gedit chat-linux.py

✍NEXT :

✍NEXT :

✍CODE :

import socket as soc
import threading as thread
import os
import pyfiglet
os.system("clear")
os.system("tput setaf 6")
title = pyfiglet.figlet_format("\t\t! WELCOME TO MY UDP CHAT APP FROM LINUX ! \n")
print(title)
print("\n ####################################################################### \n")
print("\n\t\tSO FRIEND LET'S START CHATTING \n")
print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ \n")
your_ip = input("ENTER THE YOUR IP ADDRESS HERE : ")your_port = int(input("ENTER THE YOUR PORT NUMBER HERE : "))frd_ip = input("ENTER THE FRIEND IP ADDRESS HERE : ")frd_port = int(input("ENTER THE FRIEND PORT NUMBER HERE : "))# TO CREATE A SOCKET AND BIND IP AND PORT NUMBER :skt2 = soc.socket(soc.AF_INET, soc.SOCK_DGRAM)
skt2.bind((your_ip, your_port))
# WE CAN USE THIS FUNCTION TO RECIEVING AND PRINTING THE MESSAGE :def recieve_msg():
while True:
os.system("tput setaf 2")
msgRcv = skt2.recvfrom(1024)
if msgRcv[0].decode() == "quit" or msgRcv[0].decode() == "bye bye" or msgRcv[0].decode() == "exit":
print("NOW YOUR FRIEND GOES OFFLINE.....")
os._exit(1)
print("\n\t\t\t YOUR FRIEND'S MSG --->" + msgRcv[0].decode())
# WE CAN USE THIS FUNCTION TO SENDING THE MESSAGE :def send_msg():
while True:
data = input().encode()
msgSent = skt2.sendto(data, (frd_ip, frd_port))
if data.decode() == "quit" or data.decode() == "bye bye" or data.decode() == "exit":
os._exit(1)
# WE CAN USE THIS THREAD FOR SENDING THE MESSAGE FUNCTION :t3 = thread.Thread(target=send_msg)# WE CAN USE THIS THREAD FOR RECIVING THE MESSAGE FUNCTION :t4 = thread.Thread(target=recieve_msg)# WE CAN USE THIS FUNCTION TO STARTING OUR THREADS :t3.start()
t4.start()

👉NOW, I HAVE TO RUN BOTH THE PROGRAMS SIMULTANEOUSLY :

# python chat_windows.py   [ FOR WINDOWS OS ]# pythons chat_linux.py    [ FOR LINUX OS ]

👉NOW, YOU CAN SEE THAT I AM ABLE TO CHAT BETWEEN TWO DIFFERENT TYPES OF OS.

Type “exit” or “bye bye” or “quite” for exiting the program.

I have also made one small video for this task.

✍CONCLUSION :

This tasks causes some challenges because it is using UDP protocol which also known as Connectionless protocol.

It is a connectionless protocol and not reliable So, It is not used in other chatting apps like Facebook and WhatsApp.

UDP is not reliable protocol which does not check that other system is running or not because it is connectionless and does not have any acknowledgment So, it means even if no one is receiving the message, user will keep on sending the data.

✍SOLUTION :

Solution to this challenge is TCP(Transmission Control Protocol) which will first setups the connection and then allows to send the message.

TCP provides reliable message delivery. TCP ensures that data is not damaged, lost, duplicated, or delivered out of order to a receiving process. TCP achieves this reliability by assigning a sequence number to each octet it transmits and requiring a positive acknowledgment (ACK) from the receiving TCP.

Finally I have successfully completed my this task. Thank you Vimal Daga sir for giving me such a great task. Sir your mentorship is a God gift for me to enhance my skills and I am very blessed because you are my mentor.

So guys, In the upcoming days I am going to be publish a lots of blogs and articles on different different automation tools and other technologies, So definetely follow me on Medium as well as on linkedIn.

I have also provide the link of my GitHub repository for this task which is given below for your reference.

So, Here is my linkedIn profile if you have any queries definitely comment below or DM me on linkedIn.

SEE YOU IN THE NEXT BLOG WITH MORE AMAZING TASKS.

THANK YOU🙏🙏 GUYS FOR READING MY BLOG…

SIGNING OF FORM MY SIDE 👋👋

KEEP LEARNING🙇‍♂️📖🙇….

KEEP SHARING✌✌….

--

--