Java DatagramChannel create echo server

Description

Java DatagramChannel create echo server

import java.io.IOException;
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) {
    try (DatagramChannel server = DatagramChannel.open()) {
      InetSocketAddress sAddr = new InetSocketAddress("localhost", 8989);
      server.bind(sAddr);/*ww  w . j  a  v a  2s . com*/

      ByteBuffer buffer = ByteBuffer.allocate(1024);

      while (true) {
        System.out.println("Waiting for a message from:" + 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();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related