Java – Python socket client to a Java socket server

clientjavapythonsockets

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

Best Answer

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.