Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket module, how to send integer

Tags:

python

sockets

I am reading in a value on the client side and want to send that to a server side so it can check if its prime. I'm getting an error because the server is expecting a string

server side

import socket

tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsocket.bind( ("0.0.0.0", 8000) ) 

tcpsocket.listen(2)
(client, (ip,port) ) = tcpsocket.accept()

print "received connection from %s" %ip
print " and port number %d" %port

client.send("Python is fun!") 

client side

import sys
import socket

tcpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

num = int(raw_input("Enter number: "))

tcpsocket.connect( ('192.168.233.132', 8000) ) 
tcpsocket.send(num)

Error: must be string or buffer, not int.

How can I resolve this?

like image 300
johndoe12345 Avatar asked Nov 25 '15 09:11

johndoe12345


4 Answers

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

like image 106
Serge Ballesta Avatar answered Nov 14 '22 21:11

Serge Ballesta


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

like image 45
k4ppa Avatar answered Nov 14 '22 23:11

k4ppa


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)
like image 42
Henning Lee Avatar answered Nov 14 '22 23:11

Henning Lee


In Python 3.7.2

>>>i_num = 123
>>>b_num = i_num.to_bytes(2, 'little', signed=False)
>>>b_num
b'{\x00'
>>>reverted = int.from_bytes(b_num, 'little', signed=False)
>>>i_num == reverted
True
like image 29
DevPlayer Avatar answered Nov 14 '22 21:11

DevPlayer