开发者

Python socket client to a Java socket server

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:

开发者_Python百科

I have a Java DatagramSocket that takes in n bytes:

DatagramPacket dp = new DatagramPacket(new byte[n], n);


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.


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).


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜