Java DatagramChannel create echo client

Description

Java DatagramChannel create echo client

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
  public static void main(String[] args) {
    try (DatagramChannel client = DatagramChannel.open()) {
      client.bind(null);//w w w.j  a va  2  s  . c  om
      String msg = "Hello";
      ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
      InetSocketAddress serverAddress = new InetSocketAddress("localhost", 8989);

      client.send(buffer, serverAddress);
      buffer.clear();
      client.receive(buffer);
      buffer.flip();

      int limits = buffer.limit();
      byte bytes[] = new byte[limits];
      buffer.get(bytes, 0, limits);
      String response = new String(bytes);
      System.out.println("Server responded: " + response);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}



PreviousNext

Related