2

I have a client in Python that sends data (preceded by a data length message):

s = socket.socket()
s.connect((host, port))
data = 'hello world'
s.sendall('%16s' % len(data)) #send data length
s.sendall(data) #send data
s.close()

And a server in Java that receives the data. The server uses DataInputStream.readInt() to read the data length before reading the data. However I seem to be getting really large numbers returned by readInt(). What is the problem?

2 Answers 2

7

Java expects the binary representation of your integer. You can use the struct module to generate binary representations.

In your case, this would be:

import struct
s.sendall(struct.pack('i', len(data)))

Also make sure you use the correct byte order. Java could be expecting network byte order.

Sign up to request clarification or add additional context in comments.

1 Comment

Added a link to the byte order section. Java could be expecting network byte order
2

As @mensi says, absent any other processing Java expects to receive the binary representation of the data, which differs from what Python is sending. A common solution to this sort of issue is to serialize your data -- that is, to translate it into a format more suitable for network transmission, and reconstitute the data on the receiving side.

A common serialization format for which both Python and Java have support is JSON. Recent versions of Python have the json module as part of the standard library.

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.