0

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.

ThePixelPony
  • 721
  • 2
  • 8
  • 30

1 Answers1

2

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.

Community
  • 1
  • 1
Maksym
  • 4,434
  • 4
  • 27
  • 46
  • Yeah, I considered Netty and Apache Mina and the former was too complicated and too full of features I didn't need. The latter didn't give much control. – ThePixelPony Nov 15 '14 at 20:24
  • See pretty simple example in the main netty development branch, https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/qotm – Maksym Nov 15 '14 at 20:29
  • At least using netty would be simpler than write your own UDP server implementation. – Maksym Nov 15 '14 at 20:32
  • I'm finding it quite easy with a custom library actually. Everything is so much simpler for me. This buffering thing is just a small issue. – ThePixelPony Nov 15 '14 at 21:02
  • Oh I see. Thanks for the information. I've worked out that my tile maps can hold up to 8100 tiles like this, so it'll be fine with 1024 but you've saved me a lot of debugging. :) – ThePixelPony Nov 15 '14 at 21:44