Implementing the UDP Server

The main difference with TCP is that UDP does not control the errors of the packets that are sent. The only difference between a TCP socket and a UDP socket that must specify SOCK_DGRAM instead of SOCK_STREAM when creating the socket object. Use the following code to create the UDP server:

You can find the following code in the udp_server.py file inside the udp_client_server folder:

import socket,sys
buffer=4096
host = "127.0.0.1"
port = 6789
socket_server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
socket_server.bind((host,port))

while True:
data,addr = socket_server.recvfrom(buffer)
data = data.strip()
print "received from: ",addr
print "message: ", data
try:
response = "Hi %s" % sys.platform
except Exception,e:
response = "%s" % sys.exc_info()[0]
print "Response",response
socket_server.sendto("%s "% response,addr)

socket_server.close()

In the previous code, 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 that will be continuously listening on our defined IP address and port number for any UDP messages. It is essential that this server is run prior to the execution of the Python client script or the client script will fail.