集册 Java实例教程 使用异步服务器套接字通道的服务器应用程序

使用异步服务器套接字通道的服务器应用程序

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

495
使用异步服务器套接字通道的服务器应用程序

import java.io.IOException;// 来自 N o w J a v a . c o m - 时代Java

import java.net.InetSocketAddress;

import java.net.SocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousServerSocketChannel;

import java.nio.channels.AsynchronousSocketChannel;

import java.nio.channels.CompletionHandler;

import java.nio.charset.Charset;


class Attachment {

  AsynchronousServerSocketChannel server;

  AsynchronousSocketChannel client;

  ByteBuffer buffer;

  SocketAddress clientAddr;

  boolean isRead;

}


class ConnectionHandler implements

    CompletionHandler<AsynchronousSocketChannel, Attachment> {

  @Override

  public void completed(AsynchronousSocketChannel client, Attachment attach) {

    try {
    /*
     from n o w j a v a . c o m - 时  代  Java 
    */

      SocketAddress clientAddr = client.getRemoteAddress();

      System.out.format("Accepted a connection from %s%n", clientAddr);

      attach.server.accept(attach, this);

      ReadWriteHandler rwHandler = new ReadWriteHandler();

      Attachment newAttach = new Attachment();

      newAttach.server = attach.server;

      newAttach.client = client;

      newAttach.buffer = ByteBuffer.allocate(2048);

      newAttach.isRead = true;

      newAttach.clientAddr = clientAddr;

      client.read(newAttach.buffer, newAttach, rwHandler);

    } catch (IOException e) {

      e.printStackTrace();

    }

  }


  @Override

  public void failed(Throwable e, Attachment attach) {

    e.printStackTrace();

  }

}


class ReadWriteHandler implements CompletionHandler<Integer, Attachment> {

  @Override

  public void completed(Integer result, Attachment attach) {

    if (result == -1) {

      try {

        attach.client.close();

        System.out.format("Stopped listening to the client %s%n",

            attach.clientAddr);

      } catch (IOException ex) {

        ex.printStackTrace();

      }

      return;

    }


    if (attach.isRead) {

      attach.buffer.flip();


      int limits = attach.buffer.limit();

      byte bytes[] = new byte[limits];

      attach.buffer.get(bytes, 0, limits);

      Charset cs = Charset.forName("UTF-8");

      String msg = new String(bytes, cs);


      System.out.format("Client at %s says: %s%n", attach.clientAddr, msg);


      attach.isRead = false;

      attach.buffer.rewind();

      attach.client.write(attach.buffer, attach, this);

    } else {

      attach.isRead = true;

      attach.buffer.clear();

      attach.client.read(attach.buffer, attach, this);

    }

  }


  @Override

  public void failed(Throwable e, Attachment attach) {

    e.printStackTrace();

  }

}


public class Main {

  public static void main(String[] args) {

    try (AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel

        .open()) {

      String host = 
展开阅读全文