Chat program using Socket Programming

In this blog, we are going to create a simple chat app using socket programming. In this, we are going to use UDP protocol to transfer the data from one system to another.

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 the other socket reaches out to the other to form a connection. User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite. With UDP, computer applications can send messages, in this case, referred to as datagrams, to other hosts on an (IP) network. UDP uses a simple connectionless communication model with a minimum of protocol mechanisms. UDP provides checksums for data integrity, and port numbers for addressing different functions at the source and destination of the datagram.

In this program, we will not only use socket programming but also use multithreading for the sender and the receiver to be able to send and receive the messages in real-time.

Multithreading is a process of executing multiple threads simultaneously. A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. It allows the execution of multiple parts of a program at the same time. These parts are known as threads and are lightweight processes available within the process. So multithreading leads to maximum utilization of the CPU by multitasking. Here, multithreading will help us in creating a real-time chat application.

The first step is to import all the necessary modules from the python library.

import socket
import threading
import datetime

Here, we are going to use these three modules where socket will help us in creating a UDP link between the two systems, threading will help us in creating multiple threads and datetime module will help us in printing the time.

s= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s_ip= "<IP Address>"
s_port= <Port number>
s.bind((s_ip, s_port))

These lines will help us bind the sender’s IP and port to bind them together.

def send():
while 1:
msg= input()
s.sendto( msg.encode(), (r_ip, r_port))
print('_'*(40) + time())
print("")
def receive():
while 1:
buffer_size= 1024
msg= s.recvfrom(buffer_size)
print('[' +r_ip + ']' + ' ' + msg[0].decode())
print('_'*(40) + time())
print("")

These are the two functions we have to write in order to send and receive the data. But, before sending the data we need to encode it. While receiving the data we need to justify the buffer_size (size of the data) beforehand and then decode it before printing.

That’s all, our simple chat program is created.

GitHub URL for reference

Hope you find this blog useful

Happy reading!