An Echo Server Based on the Datagram Channel - Java Network

Java examples for Network:Datagram Channel

Description

An Echo Server Based on the Datagram Channel

Demo Code

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    DatagramChannel server = DatagramChannel.open();
    InetSocketAddress sAddr = new InetSocketAddress("localhost", 5555);
    server.bind(sAddr);//from   w  ww  .j  a v  a 2s. c  om

    ByteBuffer buffer = ByteBuffer.allocate(1024);

    while (true) {
      System.out.println("Waiting for a message from" + " a remote host at "
          + sAddr);

      SocketAddress remoteAddr = server.receive(buffer);
      buffer.flip();
      int limits = buffer.limit();
      byte bytes[] = new byte[limits];
      buffer.get(bytes, 0, limits);
      String msg = new String(bytes);

      System.out.println("Client at " + remoteAddr + " says: " + msg);

      buffer.rewind();
      server.send(buffer, remoteAddr);
      buffer.clear();
    }
    // server.close();
  }
}

Result


Related Tutorials