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.