美文网首页java 编程
AIO TCP/IP 网络通信

AIO TCP/IP 网络通信

作者: 真海ice | 来源:发表于2018-02-10 12:32 被阅读0次

解释:AIO → Asynchronous input output(异步非阻塞式的输入和输出)
NIO(2.0)版本真正的异步非阻塞机制

一、 服务端

AioServer :AIO的服务端
ServerCompletionHandler: 用来处理某个客户端请求

/**
 * aio服务器端;非阻塞异步机制,JDK1.7后才有
 * @author zhb
 */
public class AioServer {
    
    // 线程池
    private ExecutorService executorService;
    // 异步线程组
    private AsynchronousChannelGroup threadGroup;
    // 异步服务通道
    public AsynchronousServerSocketChannel assc;
    
    // 开启aio服务端
    public AioServer(int port){
        try {
            // 创建一个缓存线程池
            executorService = Executors.newCachedThreadPool();
            // 创建异步线程组
            threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
            // 创建服务器通道
            assc = AsynchronousServerSocketChannel.open(threadGroup);
            // 服务通道和端口绑定
            assc.bind(new InetSocketAddress(port));
            System.err.println("Aio服务通道开启————————port" + port);
            //进行阻塞 ,不是真正的阻塞
            assc.accept(this, new ServerCompletionHandler());
            
            Thread.sleep(Integer.MAX_VALUE);    
        } catch (IOException e) {
            e.printStackTrace();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    // 主函数
    public static void main(String[] args) {
        new AioServer(Constant.serverSocketPort);
    }   

}
/**
 * 处理具体的某个客户的请求
 * @author zhb
 */
public class ServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AioServer> {

    public void completed(AsynchronousSocketChannel asc, AioServer aioServer) { 
        // 当下客户处理后,再开启一个阻塞,继续服务下一个客户端请求
        aioServer.assc.accept(aioServer, this); 
        // 读取数据
        doRead(asc);
    }

    /**
     * 读取客户端的请求信息
     * @param asc
     */
    private void doRead(final AsynchronousSocketChannel asc) {
        
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 异步读取数据
        asc.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
            // 重写没有实现的方法
            public void completed(Integer reqByteLength, ByteBuffer byteBuffer) {
                // 读取数据后。整理数据,重新复位
                byteBuffer.flip();
                // 获取读取的字节数
                System.err.println("server---获取客户端的请求的字节长度:" + reqByteLength);              
                try {
                    // 获取请求端数据
                    String reqStr = new String(byteBuffer.array(), Constant.charset).trim();
                    System.err.println("server---获取客户端的请求的请求数据为:" + reqStr);
                    // 处理请求信息
                    handlerReq(asc, reqStr);                
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

            public void failed(Throwable exc, ByteBuffer attachment) {
                exc.printStackTrace();
            }
            
        }); 
    }
    
    /**
     * 处理客户请求信息
     * @param asc
     * @param reqStr 客户请求信息
     * @throws UnsupportedEncodingException 
     * @throws ExecutionException 
     * @throws InterruptedException 
     */
    private void handlerReq(AsynchronousSocketChannel asc, String reqStr) throws UnsupportedEncodingException, InterruptedException, ExecutionException {
        
        // 处理请求,得到相应的返回信息
        String respStr = "服务器返回信息是:"+ reqStr;
        byte[] respStrByte = respStr.getBytes(Constant.charset);
        
        ByteBuffer respStrBuffer = ByteBuffer.allocate(1024);
        respStrBuffer.put(respStrByte);
        respStrBuffer.flip();
        // 异步返回响应信息
        asc.write(respStrBuffer).get();
        
        System.err.println("服务端响应成功:" +respStr);            
    }

    public void failed(Throwable exc, AioServer attachment) {
        exc.printStackTrace();
    }

}

一、 客户端

/**
 * aio 客户端请求
 * @author zhb
 */
public class ClientReq implements Runnable{
    
    // 异步socketchannel
    private AsynchronousSocketChannel asc;
    
    public ClientReq() throws IOException{
        this.asc = AsynchronousSocketChannel.open();
    }   
    public void connect(){
        this.asc.connect(new InetSocketAddress("localHost", Constant.serverSocketPort));
    }
    
    // 客户端写数据
    public void write(String reqStr) throws UnsupportedEncodingException, InterruptedException, ExecutionException{
        this.asc.write(ByteBuffer.wrap(reqStr.getBytes(Constant.charset))).get();
        read();
    }

    // 客户端读数据
    private void read() throws InterruptedException, ExecutionException, UnsupportedEncodingException {
        
        ByteBuffer respBuffer = ByteBuffer.allocate(1024);
        this.asc.read(respBuffer).get();
        respBuffer.flip();
        byte[] respByte = new byte[respBuffer.remaining()];
        respBuffer.get(respByte);
        
        String respStr = new String(respByte, Constant.charset);
        System.err.println("client收到服务端的返回信息===" + respStr);
    }

    
    public void run() {
        while(true){
        }
    }
    
    // 主线程
    public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
        
        ClientReq client = new ClientReq();
        client.connect();
        new Thread(client).start();
        Thread.sleep(1000);
        client.write("client"); 
    }

}

相关文章

  • AIO TCP/IP 网络通信

    解释:AIO → Asynchronous input output(异步非阻塞式的输入和输出)NIO(2.0)版...

  • 你需要知道的TCP/IP

    前言 TCP/IP 协议 是网络通信的基石,TCP/IP 协议 不是只有 TCP 和 IP 协议,它是整个网络通信...

  • tcp/ip的基本知识

    一.什么是tcp/ip tcp/ip是一类协议系统,它是用于网络通信的一套协议集合. 传统上来说tcp/ip被认为...

  • 从输入URL到浏览器显示页面发生了什么??

    一、网络通信互联网内各网络设备间的通信都遵循TCP/IP协议,利用TCP/IP协议族进行网络通信时,会通过分层顺序...

  • 网络通信协议简介

    TCP/IP OSI是一个理论上的七层网络通信模型,而TCP/IP则是实际运行的四层网络协议。TCP/IP包含: ...

  • OSI网络体系结构与TCP/IP协议模型

    TCP/IP与OSI最大的不同在于:OSI是一个理论上的网络通信模型,而TCP/IP则是实际上的网络通信标准。 O...

  • TCP/IP入门经典 1.TCP/IP基础知识

    第1章 什么是TCP/IP TCP/IP 是一类协议系统,它是一套支持网络通信的协议集合。 解释:在Interne...

  • TCP/IP四层通讯传输流程

    TCP/IP 通信传输流; 利用 TCP/IP 协议族进行网络通信时,会通过分层顺序与对方进行通信。发送端从应用层...

  • gen_tcp详解

    该模块 提供一组基于tcp/ip协议 socket 网络通信方法。 gen_tcp:connect/3 gen_t...

  • 《图解HTTP》读书笔记

    1. TCP/IP分层 TCP/IP协议族分为四层:应用层、传输层、网络层和数据链路层。OSI模型将网络通信分为七...

网友评论

    本文标题:AIO TCP/IP 网络通信

    本文链接:https://www.haomeiwen.com/subject/wvmctftx.html