I am trying to send integer from java to python through socket.Here Python is server and java is client.
Here is the code Python server:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost",999))
s.listen(5)
con,addr=s.accept()
num=con.recv(4)
print(int.from_bytes(num,byteorder='big'))#always zero
Java Client:
Socket s=new Socket("localhost",999);
dos=new DataOutputStream(s.getOutputStream());
dos.writeInt(2);
In python server I always receive 0 value no matter what I send in java client. I checked num value it is always single 0 byte. I also tried changing byteorder in python server but no use. What is reason of this behavior?
Edit:
I looks like I have to use 4 recv functions to read 4 bytes. I'm still confused why this happens with writeInt. With writeUTF I was able to receive 1024 bytes with single recv.
1 Answer 1
I think what's going on is you're reading bytes on the Python side, but on the Java side you're sending an int, which is a 4 byte quantity. 4 bytes will be sent as 0 0 0 2 so you're likely reading the first 0.
Two things to try, on the Python side, read four bytes and print the result of each.
Then on the Java side, instead of sending a 2, send 0x01020304 (yes that's a number). This should set each byte sent by the int to 1 2 3 4, so it's easy to read and see which piece you get.
From that you should be able to figure out how to read ints from Java. It would be handy though if Python had a facility for reading four bytes at a time from a byte array or a socket. Sorry I don't know enough Python to say what that would be.
2 Comments
DataInputStream, the complement to the DataOutputStream you are already using.)
writeIntexplicitely uses big endian order, if thereadreturned less that 4 bytes it will be converted into a 0. Could you close the socket from the Java side immediately after sending the int value? Race conditions could cause the socket to be closed before the packet has been sent to the network. Then Python will read 0 bytes (end of stream) which gives 0...