Search code examples
javaarrayssocketsdatainputstreamdataoutputstream

Is there any way to send an array of Point with DataOutputStream over a Socket?


I want to send an array of point (Point points[] = new point[20]) with DataOutputStream over a socket and be able to correctly read it with DataInputStream on the other side. I CANNOT send each element separately, it must be sent as a whole array and be able to be interpreted as a whole array.


Solution

  • See e.g. the section "Transporting Custom Objects" in Advanced Socket Programming:

    1. Put your data into a Serializable class, say MyData. (You don't really have to do this in your case, because arrays implement Serializable, but there is a chance that later you will want to send other data along with your point array...)
    2. On the sender side, create a MyData object and fill it with data. Cast socket.getOutputStream() to an ObjectOutputStream, and call its writeObject method to send the MyData object.
    3. On the receiver side, cast socket.getInputStream() to an ObjectInputStream, and call its readObject method to receive the object (you will have to cast it to MyData).

    Anyway, I would also consider using RMI. For example, you could create a PointServer, register it in the RMI registry, and access it through simple function calls in your client application. RMI is much easier to work with than sockets. For example, you don't have to design a protocol, you only need to define methods for your distributed objects.