Creating a Chat Program using UDP socket programming and Multi-threading.

Tirth Patel
2 min readJan 8, 2021

--

In this blog, we are going to create a chat program which can communicate between OS. Here, we will achieve this using UDP protocol and Multi-threading so that one of the thread will receive and other will send message. We will run the same program in Windows Machine and RHEl8 machine.

Lets start by understanding Socket. Combination of Port number and the IP address is known as Socket. Port number is just a number given to process so that any other client on behalf of root/user can run the program. In python we need to import socket library. And then create a socket using tuple of ip and port number.

We can send any message using sendto() function and receive message using recvfrom() function.

Note: Byte data can only be transferred over network. So convert your data to byte using .encode().

import socket
import threading

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = "192.168.43.174"
port = 8888
s.bind((ip, port))

# Reciever Function
def recvMsg():
while True:
x = s.recvfrom(1024)
clientIP=x[1][0]
data = x[0].decode()
print("Received Message << ",data,"\n")

# Sender Function
serverIP = "192.168.1.7"
serverPort = 7777
def sendMsg():
while True:
print()
msg = input("Type >> ")
msg = msg.encode()
s.sendto(msg, (serverIP,serverPort))

x1 = threading.Thread(target=recvMsg)
x2 = threading.Thread(target=sendMsg)

x1.start()
x2.start()

Here, ip and port is referred to ip & port of same system where you are going to run this code. So, here in my case I am running this code on RHEL8 so ip and port number will be of RHEL8. I will send message to Windows, so RHEL8 will act as client to Window and Windows system will act as server. So serverIP and serverPort are respectively of Windows Machine. Similarly, vice-versa when you run the code on Windows machine.

In the above code, x1 thread will execute recvMsg() function. That means, if any message comes from Winddows Machine, it will be read by x1 thread. Similarly if RHEL8 machine wants to send Message, it will be sent by x2 thread as x2 handles the sendMsg() function.

--

--

No responses yet