Writing a Connectionless UDP Client - Java Network

Java examples for Network:UDP

Description

Writing a Connectionless UDP Client

Demo Code

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardProtocolFamily;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class Main {
  public static void main(String[] args) throws IOException {
    CharBuffer charBuffer = null;
    Charset charset = Charset.defaultCharset();
    CharsetDecoder decoder = charset.newDecoder();
    ByteBuffer textToEcho = ByteBuffer.wrap("server!".getBytes());
    ByteBuffer echoedText = ByteBuffer.allocateDirect(65507);
    try (DatagramChannel datagramChannel = DatagramChannel
        .open(StandardProtocolFamily.INET)) {
      if (datagramChannel.isOpen()) {
        datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
        datagramChannel.setOption(StandardSocketOptions.SO_SNDBUF, 4 * 1024);
        int sent = datagramChannel.send(textToEcho, new InetSocketAddress(
            "127.0.0.1", 5555));
        System.out.println("sent " + sent + " bytes to the Echo Server!");
        datagramChannel.receive(echoedText);
        echoedText.flip();//from ww w.j a v  a 2  s .  c  om
        charBuffer = decoder.decode(echoedText);
        System.out.println(charBuffer.toString());
        echoedText.clear();
      } else {
        System.out.println("The channel cannot be opened!");
      }
    } catch (Exception ex) {
      if (ex instanceof ClosedChannelException) {
        System.err.println("The channel was unexpected closed ...");
      }
      if (ex instanceof SecurityException) {
        System.err.println("A security exception occured ...");
      }
      if (ex instanceof IOException) {
        System.err.println("An I/O error occured ...");
      }
      ex.printStackTrace();
    }
  }
}

Result


Related Tutorials