[Tutor] Talking to UDPServer
Kent Johnson
kent37 at tds.net
Tue Nov 1 19:55:51 CET 2005
Carroll, Barry wrote:
> Yes, that is exactly what I want. I need to write a program that
> communicates with an existing server, using the UDP protocol. This is
> my first time writing such a program, and I need help getting started.
Here is an example from Python Network Programming, by John Goerzen. It opens a UDP port, sends a message, then echoes any received text to the console. There is no higher-level support built in to Python, you just open a datagram socket and push data out. Google for "Python udp" for more examples.
Kent
#!/usr/bin/env python
# UDP Example - Chapter 2
import socket, sys, time
host = sys.argv[1]
textport = sys.argv[2]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
port = int(textport)
except ValueError:
# That didn't work. Look it up instread.
port = socket.getservbyname(textport, 'udp')
s.connect((host, port))
print "Enter data to transmit: "
data = sys.stdin.readline().strip()
s.sendall(data)
s.shutdown(1)
print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
while 1:
buf = s.recv(2048)
if not len(buf):
break
print "Received: %s" % buf
More information about the Tutor
mailing list