6.2. UDP Communication

6.2.1. Dependencies

TCP communication requires the NET foundation library. To use it, add the following dependency to your project’s module.ivy file:

<dependency org="ej.api" name="net" rev="1.1.2" />

6.2.2. Replacing the javax.microedition.io.Datagram class

Code using javax.microedition.io.Datagram can use java.net.DatagramSocket instead.

6.2.2.1. Write sample

The following snippet is extracted from the J2ME Javadoc.

datagram = connection.newDatagram(max);

// Reset prepares the datagram for writing new message.
datagram.reset();

// writeUTF automatically increases the datagram length.
datagram.writeUTF("hello world");

connection.send(datagram);

It can be adapted as follows:

byte[] buffer = new byte[max];

try (DatagramSocket socket = new DatagramSocket()) {
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

    // Set peer address + port
    packet.setSocketAddress(new InetSocketAddress("host.com", 79));

    // Prepares the datagram for writing message.
    packet.setData("hello world".getBytes("UTF-8"));

    // Sends the datagram
    socket.send(packet);
}

6.2.2.2. Read sample

The following snippet is extracted from the J2ME Javadoc.

datagram = connection.newDatagram(max);

connection.receive(datagram);

message = datagram.readUTF();

It can be adapted as follows:

byte[] buffer = new byte[max];

try (DatagramSocket socket = new DatagramSocket()) {
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

    // Set peer address + port
    packet.setSocketAddress(new InetSocketAddress("host.com", 79));

    // Prepares the datagram for reading message.
    packet.setLength(max);

    // Sends the datagram
    socket.receive(packet);

    // Decode the message
    int offset = packet.getOffset();
    int length = packet.getLength();
    String message = new String(buffer, offset, length, "UTF-8");
}

6.2.3. API

The API documentation of DatagramSocket is available here.

The API documentation of DatagramPacket is available here.