集册 Java实例教程 基于Future编写异步客户机

基于Future编写异步客户机

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

529
编写基于未来的异步客户端
/*来自 
 时代Java*/

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.StandardSocketOptions;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.channels.AsynchronousSocketChannel;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;

import java.util.concurrent.ExecutionException;


public class Main {

  public static void main(String[] args) {

    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

    ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !".getBytes());

    CharBuffer charBuffer;

    Charset charset = Charset.defaultCharset();

    CharsetDecoder decoder = charset.newDecoder();

    try (AsynchronousSocketChannel asyncChannel = AsynchronousSocketChannel

        .open()) {

      if (asyncChannel.isOpen()) {

        asyncChannel.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024);/* 来 自 n o w j a v a . c o m*/

        asyncChannel.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024);

        asyncChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);

        Void connect = asyncChannel.connect(

            new InetSocketAddress("127.0.0.1", 5555)).get();

        if (connect == null) {

          System.out

              .println("Local address: " + asyncChannel.getLocalAddress());

          asyncChannel.write(helloBuffer).get();

          while (asyncChannel.read(buffer).get() != -1) {

            buffer.flip();

            charBuffer = decoder.decode(buffer);

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

            if (buffer.hasRemaining()) {

              buffer.compact();

            } else {

              buffer.clear();

            }

            asyncChannel.write(ByteBuffer.wrap("test".getBytes())).get();

          }

        } 
展开阅读全文