Today I'm going to create a simple chat app in python using UDP (User Datagram Protocol ) sockets and Multi-threading concepts.
UDP:
UDP (User Datagram Protocol) is a communications protocol that is primarily used for establishing low-latency and loss-tolerating connections between applications on the internet. It speeds up transmissions by enabling the transfer of data before an agreement is provided by the receiving party.
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.
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. the network can be a logical, local network to the computer, or one that’s physically connected to an external network, with its own connections to other networks. The obvious example is the Internet, which you connect to via your ISP.
Multi-threading:
Threading is one of the most well-known approaches to attaining Python concurrency and parallelism. Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.
In our chat app Threading module will create a pool of two threads for sending and receiving messages, making a total of three threads including the main thread.
Chat App:
The code of the Simple Chat App is based on UDP but to make this app more user friendly I've used a small function which uses TCP to load your IP automatically otherwise you have to enter your IP and your friend's IP both.
he program uses recvfrom to receive the messages and sendto to send the messages at the same time as this program uses multi-threading which makes this possible.
import threading
import socket
#For receiver's IP
name=input("Enter your friend's name: ")
friend_ip=input("Enter your friend's IP: ")
#For Host IP
def ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ipv4=s.getsockname()[0]
s.close()
return ipv4
#Starting UDP Socket
ip=ip_address()
port=9459
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((ip,port))
#Recieving Message
def recv():
while True:
x=s.recvfrom(1024)
print(f"{name}-> " + x[0].decode())
if x[0].decode()=="exit":
exit()
#Sending Message
def send():
while True:
text = input()
print("You-> "+text)
s.sendto(text.encode(),(friend_ip,9459))
#Starting Thread
re = threading.Thread(target=recv)
se = threading.Thread(target=send)
re.start()
se.start()
Now lets run our code:-
First, entering friend's name and IP
Now you can see the program is working and we can send and receive message.