Java receiving Java objects as a datagram packet

advertisements

I want to send an object as a UDP packet and then receiving the object on the server. I have the client side figure out, but I can't get the server to read in the datagram correctly.

Client Code:

public void sendMessage() {
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();

        try {
            ObjectOutput oo = new ObjectOutputStream(bStream);
            oo.writeObject(asset);
            // Send it

            byte[] serializedMessage = bStream.toByteArray();

            DatagramPacket sendPacket = new DatagramPacket(serializedMessage,
                    serializedMessage.length, ipAddress, sPort);
            clientSocket.send(sendPacket);
            oo.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

Server Failed Attempt.

public void startServer() {
    try {
         serverSocket = new DatagramSocket(this.serverPort);
         serverSocket.receive(new DatagramPacket()); /*Code fails here, I realise
         * the constructor does not have input, but I can not figure out how to init
         *a buffer whose size I do not know beforehand.
         */
       this.threadPool.execute(new QueryTask(packet));
    } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
        }
}

I used the following question Sending Objects Across Network using UDP in Java to send the object in, but it did not show how he received said object.

Question 2: Is it better to create a new thread once i receive and parsed out the packet or should I create a new thread with the DatagramSocket over the Datagrampacket?

Thanks In Advance.


Create a buffer that is one bigger than the largest packet you expect to receive. Then if you ever get a packet that size, it is an overflow. Note that you should re-initialize the DatagramPacket's length before every receive, otherwise it keeps shrinking to the smallest datagram received so far.

If you can process packets quickly enough you don't really need threads at all with UDP, there being no connections to handle.