Creating simple UDP server and client

#1

if you want to test a simple UDP server either on local server or global server you can just copy the below code and run it on your machine.If you want to test with global server then change the ip address instead of local host.

import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server_address = (‘localhost’, 10000)
print >>sys.stderr, ‘starting up on %s port %s’ % server_address
sock.bind(server_address)
while True:
print >>sys.stderr, ‘\nwaiting to receive message’
data, address = sock.recvfrom(4096)

print >>sys.stderr, 'received %s bytes from %s' % (len(data), address)
print >>sys.stderr, data

if data:
    sent = sock.sendto(data, address)
    print >>sys.stderr, 'sent %s bytes back to %s' % (sent, address)

run the above code by running the command sudo python code.py.You can put your desired port number instead of the above.
for allowing the ports and killing the process refer the link below.

if you want to ensure your UDP server is working, then from another terminal in your local system you have to run another code that is UDP_client.below is the code run it then you would be seeing the messages from UDP server and UDP client.

import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server_address = (‘localhost’, 10000)
message = ‘This is the message. It will be repeated.’

try:

# Send data
print >>sys.stderr, 'sending "%s"' % message
sent = sock.sendto(message, server_address)

# Receive response
print >>sys.stderr, 'waiting to receive'
data, server = sock.recvfrom(4096)
print >>sys.stderr, 'received "%s"' % data

finally:
print >>sys.stderr, ‘closing socket’
sock.close()

make sure ports are same and enabled.

1 Like