I'm coding a school excercise using UDP sockets in python and I need to exchange some information (e.g., ints, strings, etc.) between server and client.
I wrote this functions to asure a message sent from the server is received on the client side and vice versa:
import socket
BUFFER_SIZE = 1024
def send_udp_mgs(origin, destination, msg):
msg = str(msg).encode('utf8')
origin.sendto(msg, destination) # sending message
# I never receive confirmation
opt, _ = origin.recvfrom(BUFFER_SIZE) # Code stucks here
opt = opt.decode('utf8')
print(opt)
def receive_udp_msg(destination):
msg, origin = destination.recvfrom(BUFFER_SIZE) # receiving message OK
# This is the message sent as confirmation but is never received
destination.sendto("CHECK".encode('utf8'), origin) # sent but not received
msg = msg.decode()
return msg
I would expect the code to work properly with the function receiving the confirmation after sending the message but it gets stuck waiting for the confirmation. The client sends the confirmation but the server never receives it. Other than that, the client receives the message well, it's only the confirmation back to the server that fails.
This is the server code:
def client_thread (s, c):
print("Connection petition from", c)
global n_cons
cport = PORT + n_cons
send_udp_mgs(s, c, cport)
return
# UDP socket acting as server
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((IP, PORT))
while True:
data, addr = s.recvfrom(BUFFER_SIZE)
if data.decode() == CONNECT:
n_cons += 1
try:
Thread(target=client_thread, args=(s,), kwargs={'c':addr}).start()
except:
print("Error creating thread")
break
Client code
c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s = (IP, PORT)
# Connecting to the server
c.sendto(CONNECT.encode('utf8'), s)
cport = receive_udp_msg(c)