Server code:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # server UDP socket
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bypass OS lock on port
s.bind((socket.gethostname(), 9999)) # bind socket to host and port 9999
while True:
message, ip = s.recvfrom(1024) # receive data passed through socket
print "Server:\n\tMessage \"{}\" received...\n\tIt has a length of {}".format(
message, len(message))
s.sendto(str(len(message)), (socket.gethostname(), 9999)) # send message length in bytes back to client
s.close() # close UDP connection with client
sys.exit(0) # terminate server process
Client code:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((socket.gethostname(), 9999))
message = "Pointless text."
print "Client:\n\tSending message \"{}\" to the server...\n\tIt has a length of {}".format(
message, len(message))
s.sendto(message, (socket.gethostname(), 9999))
while True:
response, ip = s.recvfrom(1024)
if int(response) == len(message):
print "Client:\n\tThe server returned count {} which is equal to the client's count of {}.".format(response, len(message))
else:
print "Client:\n\tThe server returned count {} which is not equal to the client's count of {}.".format(response, len(message))
s.close()
Output:
Running client in UDP mode...
Running server in UDP mode...
Client:
Sending message "Pointless text." to the server...
It has a length of 15
Server:
Message "Pointless text." received...
It has a length of 15
The client side recvfrom
never gets triggered and I can't figure out why.
Here are the complete client and server files if you want to test them directly on your machine like so:
python2.7 server udp & python2.7 client udp
In your server code, you are sending the result to the server's address ( 9999
), not the client's ( ip
).
Try this:
s.sendto(str(len(message)), ip) # send message length in bytes back to client
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.