I have an integer, which i want to send across from a socket to another in python. Lets say this integer a=2. How do i send this integer across to a socket over a connection.
Currently, i have done the following code:
server_socket.send(str(a)) #Server side
b=int(client_socket.recv(512)) #Client side
but the call to int() gives me error, saying that its not of valid length. i am basically not getting what argument to put in the recv() method.
You are sending an 4-byte integer across the line but you are trying to receive 512 bytes, so it’s just allocating an unallocated bit of memory like so:
000000000000000000000000000[…snip a bunch more bytes…]
….with the bytes it receives, so it looks like:
F34D5DD20000000000000000000[…snip a bunch more bytes…]
So you then have a 512-byte array of bytes, which can’t be converted to an int. recv(4) instead, or better yet use a protocol that handle dynamic lengths (which is the only actually stable solution to this problem, you can’t expect recv(4) to solve the problem).