Passing Messages with Socket Datagrams
Credit: Jeff Bauer
Problem
You need to communicate small messages between machines on a TCP/IP network in a lightweight fashion, without needing absolute assurance of reliability.
Solution
This is what the UDP protocol is for, and Python makes it
easy for you to access it, via datagram sockets. You can write a server
(server.py)
as follows:
import socket
port = 8081
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Accept UDP datagrams, on the given port, from any sender
s.bind(("", port))
print "waiting on port:", port
while 1:
# Receive up to 1,024 bytes in a datagram
data, addr = s.recvfrom(1024)
print "Received:", data, "from", addrAnd you can write a client (client.py) as
follows:
import socket
port = 8081
host = "localhost"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto("Holy Guido! It's working.", (host, port))Discussion
Sending short text messages with socket datagrams is simple to implement and provides a lightweight message-passing idiom. Socket datagrams should not be used, however, when reliable delivery of data must be guaranteed. If the server isn’t available, your message is lost. However, there are many situations in which you won’t care whether the message gets lost, or, at least, you won’t want to abort a program just because the message can’t be delivered.
Note that the sender of a UDP datagram (the client in this example)
does not need to bind the socket before calling the
sendto method. On the other hand, ...