Search code examples
javadatagram

int array sent and receive in datagram socket programming in java


I try to send a integer array via datagram socket. What is the best way to accomplish this. MY sending code is:

public void sendObj(Object obj) {
        try{
            byteArr = new ByteArrayOutputStream();
            objOut = new ObjectOutputStream(byteArr);
            objOut.writeObject(obj);
            byte[] b = byteArr.toByteArray();
            DatagramPacket dgram = new DatagramPacket(b, b.length, InetAddress.getByName("230.0.0.1"), 4446); // multicast
            socket.send(dgram);
            System.out.println("Package is sent!");
        }catch(Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

And receiving code is:

byte[] b = new byte[65535];
ByteArrayInputStream b_in = new ByteArrayInputStream(b);
DatagramPacket dgram = new DatagramPacket(b, b.length);

socket.receive(dgram); // blocks
ObjectInputStream o_in = new ObjectInputStream(b_in);
Object o = o_in.readObject();
dgram.setLength(b.length); // must reset length field!
b_in.reset(); //

However when I receive it gives StreamException for unknown header value 00000


Solution

  • We solved that problem by a basic changes. We used a string like "100200300..." to symbolize the array by separating element with two 0' so in that way we did not use ArrayList.