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

编写无连接的UDP客户端

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

420
编写无连接UDP客户端

import java.io.IOException;/** N o w  J a v a  . c o m 提供 **/

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());/*来自 N o w  J a v a  .   c o m*/

    ByteBuffer echoedText = ByteBuffer.allocateDirect(65507);

    try (DatagramChannel datagramChannel = DatagramChannel

        .open(StandardProtocolFamily.INET)) {

      if (datagramChannel.isOpen()) {

        datagramChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);

        datagramChannel.setOption(StandardSocketOptions.SO_SNDBUF, 4 * 1024);

        int sent = datagramChannel.send(textToEcho, new InetSocketAddress(

            "127.0.0.1", 5555));

        System.out.println("sent " + sent + " bytes to the Echo Server!");

        datagramChannel.receive(echoedText);

        echoedText.flip();

        charBuffer = decoder.decode(echoedText);

        System.out.println(charBuffer.toString());

        echoedText.clear();

      } else {

        System.out.println("The channel cannot be opened!");

      }

    } catch (Exception ex) {

      if (ex instanceof ClosedChannelException) {

        System.err.println(
展开阅读全文