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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With