集册 Java实例教程 编写连接的UDP客户端

编写连接的UDP客户端

欢马劈雪     最近更新时间:2020-01-02 10:19:05

489
编写连接的UDP客户端
/**
来 自 时   代    Java - nowjava.com
**/

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 {/** from 时 代 J a v a 公 众 号 - nowjava.com**/

    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();

          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(
展开阅读全文