how to send an int over a socket
Tom Brown
brown at esteem.com
Fri Feb 4 21:54:52 EST 2005
On Friday 04 February 2005 18:27, Tom Brown wrote:
> Hi,
>
> I have what seems to be a simple problem. But I can not for the life of me
> find a way to send an integer over a socket. The send method will only
> accept strings. Here is what I am trying to do:
>
> testmessage = 'test message'
> msglen = len(testmessage)
> sock.send(msglen)
> sock.send(testmessage)
>
> Now, I know I can do this:
>
> testmessage = 'test message'
> sock.send('\xC') # send hard coded length of testmessage in hex in string
> sock.send(testmessage)
>
> However, in my actual program I will not know the length of testmessage in
> advance. So how do I convert msglen into a suitable format for the send
> method?
>
> Thanks,
> Tom
Ok, I think I've found what I was looking for. The marshal.dumps() function
will convert my integer into a string representation of a fixed size. This
way, on the other side, I know how many bytes to read to get the size of the
string.
Thanks,
Tom
More information about the Python-list
mailing list