Writing a Connected UDP Client - Java Network

Java examples for Network:UDP

Description

Writing a Connected 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)) {
      datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
      datagramChannel.setOption(StandardSocketOptions.SO_SNDBUF, 4 * 1024);
      if (datagramChannel.isOpen()) {
        datagramChannel.connect(new InetSocketAddress("127.0.0.1", 5555));
        if (datagramChannel.isConnected()) {
          int sent = datagramChannel.write(textToEcho);
          System.out.println("I have successfully sent " + sent
              + " bytes to the Echo Server!");
          datagramChannel.read(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 connected!");
        }
      } 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