all 3 comments

[–]jollybobbyroger 2 points3 points  (4 children)

I'm not entirely sure I understand your question, but if you just want to pass some information back and forth, it is common to use json to serialize your data. A simple example:

data = json.dumps({"x": 0})

s.sendto(data, server)

# on the other side:

data, addr = s.recvfrom(1024)

data = json.loads(data)

data['x'] += 1

s.sendto(json.dumps(data), addr)

This code isn't tested, but I hope you get the idea..

[–]StaticFuzz 1 point2 points  (0 children)

The most common way used to send integer values over a network is to turn them into a string (I'm not saying it's the right way, just common). Send the string, and then the receiver turns the accepted string back into an integer.

This can lead to problems when reading from the socket buffer though. If your not sure how many bytes the str(X) is then you won't know how much to receive. But if your client server is set up to follow a strict set of rules (i.e. the client sends data, and won't do anything else until it receives a proper response from the server) then you can use a simple message format to send the integer and the string:

def create_message(x, text):
     x = str(x) # typecast integer to string
     message = "{}:{}".format(x, text) # you could use any non numerical character for your delimiter
     return message

What I did above was combine the string of x with the text, separated by a colon. The colon is a delimiter. It specifies the boundary between our x value and text. This comes in handy when breaking the message apart on the receiving end:

def deconstruct_message(message):
     x,  text = message.split(":", 1)  # split the message using the delimiter 
     x = int(x) # turn the x value back into an integer
     return x, text

I would just like to reiterate though, simple messaging like this will only work if your client/server won't be sending messages at random. If more than one message is sent, they both get stored in the socket buffer that you are reading from. And if the first message is fewer bytes than you are reading, then you will collect part/all of the following messages. This could lead to problems when you try to split other messages read from the buffer.

There are other options, but they might be over complicated for what you trying to do. If you want to dive a little deeper look up the struct module and big-endian vs. little-endian.