4

I'm currently working on getting a python socket to send an integer to a java socket, so the java socket can read in a byte array that represents a string after this step.

I've tried sending the int in a struct but that returns a massive number on the java side.

p = struct.pack('i', len(data))
clientsocket.send(p)
6
  • 1
    You need to look into different serialization libraries, things like msgpack allow you to send data in a uniform manner so that all languages can understand the data. Commented Jan 21, 2016 at 22:07
  • 2
    Maybe the byte order is wrong... I guess you're working on an Intel platform. That would be Little Endian. Internet and Java VM standard is Big Endian. So maybe all bytes are just in the wrong order (istead of 4-3-2-1 python might send 1-2-3-4). Maybe that is the problem. I have no clue of python btw ;-) Commented Jan 21, 2016 at 22:08
  • I would personally not use serialization at all, but look at just sending raw data to the socket. In Java you do this with a raw Input/OutputStream and DataInput/OutputStream. Commented Jan 21, 2016 at 22:11
  • Thanks guys, turns out it was the byte order that was incorrect. Jay could you put that as an answer so I can mark it as the solution? Commented Jan 21, 2016 at 22:20
  • Oh and William I'm definitely going to look into msgpack. Thanks for that suggestion! Commented Jan 21, 2016 at 22:20

1 Answer 1

2

https://docs.python.org/2/library/struct.html

Check out 7.3.2.1. When sending any data over the network always convert it to network byte-order. Your above code would be:

p = struct.pack('!i', len(data))
clientsocket.send(p)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.