How to use python to implement UDP server/client?

As we know, python has a module named SimpleHTTPServer can be used to create a web server in one line:

$ python -m SimpleHTTPServer 80

How can we create an UDP server by Python? Here is a quick example:

Python UDP Server:

#!/usr/bin/env python
# UDP Echo Server -  udpserver.py
import socket
import traceback

host = ''
port = 8888

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))

while 1:
    try:
        message, address = s.recvfrom(8192)
        print "Got data from", address, ": ", message
        s.sendto(message, address)
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        traceback.print_exc()

Python UDP Client:

#!/usr/bin/env python
# UDP Client - udpclient.py
import socket, sys

host = sys.argv[1]
textport = sys.argv[2]

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
    port = int(textport)
except ValueError:
    port = socket.getservbyname(textport, 'udp')
s.connect((host, port))
while 1:
    print "Enter data to transmit:"
    data = sys.stdin.readline().strip()
    s.sendall(data)
    print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
    buf = s.recv(2048)
    if not len(buf):
        break
    print "Server replies: ",
    sys.stdout.write(buf)
    print "\n"
Share Button

Leave a comment

Your email address will not be published. Required fields are marked *