I'm trying to get one of the examples from Foundation of Python
Network Programming to work. Specifically this is the UDP example
from Ch 3. First there is the server:
#!/usr/bin/env python
# UDP Echo Server - Chapter 3 - udpechoserver.py
import socket, traceback, time
host = '127.0.0.1' # Bind to all
interfaces
port = 51423
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 message '%s' from %s" % (message, address)
# Echo it back
s.sendto(message, address)
print "Sent response to '%s'" % (address,)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
Next I have a client written in Ruby, which works. I am posting thing
not to start a Ruby/Python flame war, but to simply prove that the
server works and there are no weird networking issues that would
prevent the Python client from working. The Ruby code is:
#!/usr/bin/env ruby
require 'socket'
socket = UDPSocket.new
socket.connect ARGV[0], ARGV[1]
puts "Enter data to transmit: "
data = STDIN.gets.chomp
socket.send data, 0
puts "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
loop do
buf = socket.recvfrom(2048)
puts buf.first
end
When I start the server and run that, the output looks like this:
$ ch02/udp.rb 127.0.0.1 51423
Enter data to transmit:
foobar
Looking for replies; press Ctrl-C or Ctrl-Break to stop.
foobar
Now, when I try the python example:
#!/usr/bin/env python
# UDP Example - Chapter 2 - udp.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:
# That didn't work. Look it up instead.
port = socket.getservbyname(textport, 'udp')
s.connect((host, port))
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."
while 1:
buf = s.recvfrom(2048)
sys.stdout.write(buf[0])
I don't ever get a response:
$ ch02/udp.py 127.0.0.1 51423
Enter data to transmit:
foobar
Looking for replies; press Ctrl-C or Ctrl-Break to stop.
The server sees the message and says it has sent a reply:
Got message 'foobar' from ('127.0.0.1', 49623)
Sent response to '('127.0.0.1', 49623)'
Any ideas as to why this doesn't work?
--
http://mail.python.org/mailman/listinfo/python-list