Listening on UDP socket
I am using this code to receive data from a UDP socket and return it as string:
byte[] receiveData = new byte[MAX_PACKET_SIZE];
DatagramPacket receivedPacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivedPacket);
return new String(receivedPacket.getData(), 0, receivedPacket.getLength());
I set MAX_PACKET_SIZE to 1024 which causes Java to reserve a 1024bit long byte[] everytime a packet arrives. This causes a lot of overhead if the packet is much smaller than 1024 byte.
Is there a better way to accomplish this? Maybe with some kind of while() read cycle? I am not开发者_开发问答 very familiar with Java yet. :)
You can reuse the packet if you want to avoid the overhead of creating mutliple arrays (although short-lived objects actually have very little impact on performance anyway).
Note that you can't read a UDP datagram in chunks, as anything beyond the end of the DatagramPacket you pass to receive is discarded.
Edit - I checked, and DatagramChannel.receive is pretty much the same. You really do need to ensure that your buffer is big enough to receive the largest possible valid datagram.
精彩评论