Achieve parallelism in Your own server with UDP protocol

Urvishtalaviya
2 min readApr 15, 2021

This article shows how to create a server with UDP protocol in the python programming language. And also how to handle more than one request at the same time.

We all know the concept of multi-threading. Yes, threading is the way to achieve parallelism for the server. Python has a module called a thread, that can help us to create threads in our program. I assume that you already know how to create threads in python, if not then don’t worry it not a big deal. You will see how to create threads in the blog.

server.py

#importing libraries for networking
#and threading
import time
import socket
import threading
#protocol : UDP
protocol = socket.SOCK_DGRAM
#net address family : IPv4
net_address = socket.AF_INET
#socket module object
sckt = socket.socket(net_address, protocol)
#declaring variables for IP and Port
#for this server
ip = "192.168.43.137"
port = 1234
#binding the IP address and Port
#IP + Port = Socket
sckt.bind((ip, port))
#receiving the input from the network
#recvfrom method only works with UDP protocol
#recvfrom takes number as an input
#the number define the maximum input size
def func(*x):
print("msg: {0} from: {1}:{2}".format(x[0].decode(), x[1][0], x[1][1]))
time.sleep(10)
print("process for {0} has been finished".format(x[1][0]))
#create three threads for achieving
#parallelism on the server
while True:
x = sckt.recvfrom(1024)
thread = threading.Thread(target=func, args=(x))
thread.start()

The code is itself self-explanatory, so I guess I don’t require to explain it. In order to explain to you about multi-threading, I have used the sleep function that runs the process a little longer😜 else there is no meaning to use thread in here.

client.py

#importing library for networking
import socket
#Initilazing object with UDP and IPv4
sckt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#sendto method will send the data to
#192.168.43.137:1234 with in byte type
sckt.sendto("Hi!! 6".encode(), ("192.168.43.137", 1234))

Output

Here, I had sent 4 messages from the same client program, see on the black screen it handled it very well.

--

--

Urvishtalaviya

Competitive Programmer | Machine Learning Enthusiastic | Bigdata Enthusiastic