So after looking around for a suitable library, I've decided to make my own and here is part of it.
try {
DatagramSocket serverSocket = new DatagramSocket(client_port);
byte[] receiveData = new byte[1024];
byte[] finalData;
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
erverSocket.receive(receivePacket);
if (this.address == receivePacket.getAddress() && this.server_port == receivePacket.getPort()) {
** handler.onMessage(receivePacket.getData()); **
}
}
} catch (IOException ex) {
Logger.getLogger(PacketHandler.class.getName()).log(Level.SEVERE, null, ex);
This code is obviously ran asynchronously.
The receiveData is set to 1024, which is terribly wasteful. It also means that anything bigger than 1024 gets split into two or more "Events" fired by the library.
I was wondering how it is possible to make a buffer, as I've gone completely blank. Essentially, you'd have to count the number of bytes somehow and push it into a new array.
So I'm basically asking for an efficient method, which doesn't have to include code.
Are you sure that you need to use UDP for it? Seems like you should change it to TCP impelementation. Do you want to use netty for it ? See here.
1024 bytes it's normal safe value for UDP datagaram, making it bigger can bring issues with router. (See https://stackoverflow.com/a/13089776/3502543).
If you don't want to use netty, you should provide something similar to DelimiterBasedFrameDecoder.
edited.