0
votes

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.

2
I know you are specifically asking about Datagram UDP connections, but have you considered RMI/JAX-WS(SOAP)/JAX-REST? - dngfng
Also you may find that this answers your question: stackoverflow.com/questions/3997459/… - dngfng

2 Answers

2
votes

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.

1
votes

As you already seen, datagramm packet needs buffer to write stuff into. I would create buffer which is just big enough for intendet data (UDP specifies 65K for IPV4 and 4G for IPV6). And if I were you , I would not use java.io serialisation as it is going to break on every class change ( or even sometimes compiler change ). Use more robust serialisation means like JSON ( with jackson / gson ) or XML or protobuf