UDP client-server problem

Heiko Wundram heikowu at ceosg.de
Tue Jul 15 21:03:40 EDT 2003


This should work:

Server
======

import socket
import time

# Constants.
PORT = 37

# Create and bind the socket which listens for packets.
srvsocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
svrsocket.bind(('',PORT))

while 1:
	# Block waiting for packet.
	data, address = svrsocket.recvfrom(256)
	print "Client sent:", data
	print "Client at:", address
	# Got a packet, reply to address packet came from.
	srvsocket.sendto(str(time.time()),address)

Client
======

import socket

# Constants.
PORT = 37

# Create new socket, let it bind to an OS-chosen port.
clisocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

while 1:
	data = raw_input("Enter what the server receives.")
	if data:
		# Send data to server, irrelevant what.
		clisocket.sendto(data,("localhost",PORT))
		# Block waiting for reply.
		data, address = clisocket.recvfrom(256)
		print "Server sent time:", data
	else:
		break

Look at the above code. There were several errors in your original
implementation, e.g. that time never got updated while the server ran,
and several other things. I also don't see the need for a Tijd class.

HTH!

Heiko.

PS: The above code is untested, if there's something wrong, my bad... :)
PPS: Read the UNIX TCP/IP Network Programming FAQ if you're into socket
programming! Google for it, I currently don't know the URL...






More information about the Python-list mailing list