views:

484

answers:

3

Hello, I have a Java socket server that is expecting exactly n bytes from some port. I want to write a Python clients that just sends bytes on some port to the Java server.

Since Python does not have primitives, I'm not sure to send exactly n bytes. Any suggestions?

More details:

I have a Java DatagramSocket that takes in n bytes:

DatagramPacket dp = new DatagramPacket(new byte[n], n);
+1  A: 

somesocket.send takes a byte-string argument s -- just ensure that len(s) == n, and you will be sending exacty n bytes. What do "primitives" have to do with it?!

To turn arbitrary bunches of data into byte strings (and back), see the struct module in Python's standard library (for the specific but frequent case of homogeneous arrays of simple types such as floats, the array module is often even better).

Alex Martelli
So say I want to send the double 3.4. Java doubles are 64 bits, so I would need to encode a python 3.4 into 8 bytes. How would I do this? I've never really pushed bits around in python so this is rather confusing.
Elben Shira
@elben, `struct.pack`, see http://docs.python.org/library/struct.html .
Alex Martelli
+1  A: 

If you are using a datagram socket (e. g. the UDP protocol over IP), the Socket API guarantees that if your n is less than the maximum payload size, then your data will be sent in a single packet. So just calling socket.send would be sufficient.

The easiest way to send data over a stream socket is to use the socket.sendall method, as send for streams doesn't guarantee that all the data is actually sent (and you should repeatedly call send in order to transmit all the data you have). Here is an example:

>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('localhost', 12345))
>>> data = 'your data of length n'
>>> s.sendall(data)

As @Alex has already mentioned, there is nothing related to some kind of "primitives" in Python. It is just and issue with the Socket API.

Andrey Vlasovskikh
A: 

Thanks to your answers, I figured out what I was looking for. What I wanted was struct.unpack and struct.pack to allow me to pack the python float 1.2345 to a string representation of a C double.

That is:

>>> struct.pack('d', 1.2345)
'\x8d\x97n\x12\x83\xc0\xf3?'
>>> struct.unpack('d', struct.pack('d', 1.2345))[0]
1.2344999999999999

Thanks!

Elben Shira