Socket module, how to send integer

Never send raw data on a stream without defining an upper level protocol saying how to interpret the received bytes.

You can of course send integers in either binary or string format

  • in string format, you should define an end of string marker, generally a space or a newline

    val = str(num) + sep # sep = ' ' or sep = `\n`
    tcpsocket.send(val)
    

    and client side:

    buf = ''
    while sep not in buf:
        buf += client.recv(8)
    num = int(buf)
    
  • in binary format, you should define a precise encoding, struct module can help

    val = pack('!i', num)
    tcpsocket.send(val)
    

    and client side:

    buf = ''
    while len(buf) < 4:
        buf += client.recv(8)
    num = struct.unpack('!i', buf[:4])[0]
    

Those 2 methods allow you to realiably exchange data even across different architectures


tcpsocket.send(num) accept a string, link to the api, so don't convert the number you insert to int.


I found a super light way to send an integer by socket:

#server side:
num=123
# convert num to str, then encode to utf8 byte
tcpsocket.send(bytes(str(num), 'utf8'))

#client side
data = tcpsocket.recv(1024)
# decode to unicode string 
strings = str(data, 'utf8')
#get the num
num = int(strings)

equally use encode(), decode(), instead of bytes() and str():

#server side:
num=123
# convert num to str, then encode to utf8 byte
tcpsocket.send(str(num).encode('utf8'))

#client side
data = tcpsocket.recv(1024)
# decode to unicode string 
strings = data.decode('utf8')
#get the num
num = int(strings)

Tags:

Python

Sockets