Writing a UDP Server - Java Network

Java examples for Network:UDP

Description

Writing a UDP Server

Demo Code

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.StandardProtocolFamily;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;

public class Main {

  public static void main(String[] args) {
    ByteBuffer echoText = 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);
        datagramChannel.bind(new InetSocketAddress("127.0.0.1", 5555));
        System.out.println("Echo server was binded on:"
            + datagramChannel.getLocalAddress());
        while (true) {
          SocketAddress clientAddress = datagramChannel.receive(echoText);
          echoText.flip();/*from  w  ww.ja v a2s  .  c o  m*/
          System.out.println("I have received " + echoText.limit()
              + " bytes from " + clientAddress.toString()
              + "! Sending them back ...");
          datagramChannel.send(echoText, clientAddress);
          echoText.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