Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an integer over a socket to a Java application using python?

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?

like image 236
XåpplI'-I0llwlg'I - Avatar asked Apr 12 '26 06:04

XåpplI'-I0llwlg'I -


2 Answers

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.

like image 53
mensi Avatar answered Apr 14 '26 19:04

mensi


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.

like image 38
larsks Avatar answered Apr 14 '26 18:04

larsks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!