Welcome, guest | Sign In | My Account | Store | Cart

Sending short text messages with socket datagrams is simple to implement and provides a very lightweight message passing idiom.

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# server.py
import socket
port = 8081
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
print "waiting on port:", port
while 1:
    data, addr = s.recvfrom(1024)
    print data

---

# client.py
import socket
port = 8081
host = "localhost"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", 0))
s.sendto("Holy Guido! It's working.", (host, port))

Socket datagrams should not be used where reliable delivery of data must be guaranteed. If the server isn't available, your message is lost. However, there are many situations where: (1) you don't care whether the message gets lost; or (2) you don't want to abort a program just because the message can't be delivered.

Don't use the above code to send large datagram messages, especially under Windows -- which apparently doesn't respect the buffer limit. To send larger messages, you will probably want to do something like this:

BUFSIZE = 1024
while msg:
    s.sendto(msg[:BUFSIZE], (host, port))
    msg = msg[BUFSIZE:]

I often use socket datagrams for debugging, especially where the application spans more than one machine.