Implementing the UDP server

When working with UDP, the only difference if we compare this to working with TCP in Python is that when creating the socket, you have to use SOCK_DGRAM instead of SOCK_STREAM. Use the following code to create the UDP server.
You can find the following code in the udp_server.py file inside the udp folder:

#!/usr/bin/env python3

import socket,sys

UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT = 12345
buffer=4096

socket_server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #UDP
socket_server.bind((UDP_IP_ADDRESS,UDP_PORT))

while True:
print("Waiting for client...")
data,address = socket_server.recvfrom(buffer)
data = data.strip()
print("Data Received from address: ",address)
print("message: ", data)
try:
response = "Hi %s" % sys.platform
except Exception as e:
response = "%s" % sys.exc_info()[0]

print("Response",response)
socket_server.sendto(response.encode(),address)

socket_server.close()

In the preceding code for implementing the UDP server, we see that socket.SOCK_DGRAM creates a UDP socket, and data, addr = s.recvfrom(buffer), returns the data and the source's address.

Now that we have finished our server, we need to implement our client program. The server will be continuously listening on our defined IP address and port number for any received UDP message. It is essential that this server is run prior to the execution of the Python client script, or the client script will fail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset