首页 > 编程语言 >java网络编程-AIO

java网络编程-AIO

时间:2023-03-04 20:45:36浏览次数:39  
标签:java nio 编程 AIO ByteBuffer import public channel

java1.4提供的NIO已经很厉害了,大神们再接再厉,在java1.7又提出了新的NIO2.0——AIO

AIO是真正的异步非阻塞IO,Linux底层依赖epoll,我们先看个案例

//服务端
public class AIOServer {
    private static int port =8080;
    public static void main(String[] args) {
        AsyncServerHandler asyncServerHandler = new AsyncServerHandler(port);
        new Thread(asyncServerHandler).start();
    }
}


//
package aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannel;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncServerHandler implements Runnable{
    public CountDownLatch latch;
    public AsynchronousServerSocketChannel channel;
    public AsyncServerHandler(int port) {
        try {
            channel=AsynchronousServerSocketChannel.open();
            channel.bind(new InetSocketAddress(port));
            System.out.println("服务端已启动");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        latch=new CountDownLatch(1);
        channel.accept(this,new AcceptHandler());
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}



//
package aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ReadeHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel channel;

    public ReadeHandler(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        attachment.flip();
        byte[] bytes = new byte[attachment.remaining()];
        attachment.get(bytes);
        try {
            String s = new String(bytes, "UTF-8");
            System.out.println("server receive:" + s);
            doWrite("hello," + s);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void doWrite(String result) {
        byte[] bytes = result.getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        writeBuffer.put(bytes);
        writeBuffer.flip();
        channel.write(writeBuffer, writeBuffer, new WriteHandler(channel));
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            this.channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



//
package aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class WriteHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel channel;

    public WriteHandler(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        if (buffer.hasRemaining()) {
            channel.write(buffer, buffer, this);
        } else {
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            channel.read(readBuffer, readBuffer, new ReadeHandler(channel));
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            this.channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

package aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncServerHandler> {
    @Override
    public void completed(AsynchronousSocketChannel channel, AsyncServerHandler serverHandler) {
        serverHandler.channel.accept(serverHandler, this);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        channel.read(buffer, buffer, new ReadeHandler(channel));
    }

    @Override
    public void failed(Throwable exc, AsyncServerHandler serverHandler) {
        exc.printStackTrace();
        serverHandler.latch.countDown();
    }
}

 

 

客户端代码

package aio;

import java.util.Scanner;

public class AIOClient {
    private static int port = 8080;
    private static String host = "127.0.0.1";

    public static void main(String[] args) {
        AsyncClientHandler asyncClientHandler = new AsyncClientHandler(host, port);
        new Thread(asyncClientHandler).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String msg = scanner.nextLine();
            asyncClientHandler.sendMsg(msg);
        }
    }
}


//
package aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class ClientReadeHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel channel;
    private CountDownLatch latch;

    public ClientReadeHandler(AsynchronousSocketChannel channel,CountDownLatch latch) {
        this.channel = channel;
        this.latch=latch;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        attachment.flip();
        byte[] bytes = new byte[attachment.remaining()];
        attachment.get(bytes);
        try {
            String s = new String(bytes, "UTF-8");
            System.out.println("client receive:" + s);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        System.out.println("数据读取失败");
        try {
            this.channel.close();
            this.latch.countDown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


//
package aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class ClientWriteHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel channel;
    private CountDownLatch latch;

    public ClientWriteHandler(AsynchronousSocketChannel channel,CountDownLatch latch) {
        this.channel = channel;
        this.latch=latch;
    }

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        if (buffer.hasRemaining()) {
            channel.write(buffer, buffer, this);
        } else {
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            channel.read(readBuffer, readBuffer, new ClientReadeHandler(channel,latch));
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            this.channel.close();
            latch.countDown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

标签:java,nio,编程,AIO,ByteBuffer,import,public,channel
From: https://www.cnblogs.com/wangbin2188/p/17179062.html

相关文章

  • java项目自动化单元测试
    对于我们开发人员来说,单元测试一定不会陌生,但在各种原因下会被忽视,尤其是在我接触到的项目中,提测阶段发现各种各样的问题,我觉得有必要聊一下单元测试。为了写而写的单元测......
  • Java Swing项目使用Idea UI Designer设计插件无法启动问题解决方案
    起因最近整理一下以前写的swing项目,结果发现跑不起来了,具体表现为与视图表绑定的Java类的各属性为NULL(插件没有初始化绑定的类对象),导致项目无法启动。(报空指针异常)问题排......
  • java8新特性-Stream基础
    Stream是跟随Lambda表达式一起发布的java8新特性。是支持串行和并行处理数据的工具。有四种类型的Stream。在StreamShape枚举中定义了Stream的类型。分别是REFERENCE(引用流......
  • Java——NIO三大核心部分
    在JavaNIO中,选择器(Selector)、通道(Channel)和缓冲区(Buffer)是三个核心组件。选择器:它允许一个单独的线程来监视多个输入通道。你可以注册多个通道使用一个选择器,然后使用......
  • JavaSE——StringBuilder方法
    StringBuilder可以看成是一个容器,创建之后里面的内容是可变的。packagecom.zhao.stringdemo;publicclassStringDemo2{publicstaticvoidmain(String[]args......
  • JavaScript 文档的加载
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> /* *浏览器在加载一个页面时,是按照自上向下......
  • java-spring纯注解开发
    1、创建配置类替代配置文件/***<p>描述:配置信息,省去编写配置文件*/@Configuration@ComponentScan("cn.tjhis")publicclassSpringConfig{}2、实现类......
  • JavaScript dom查询
    <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN""http://www.w3.org/TR/html4/strict.dtd"><html> <head> <metahttp-equiv="Content-Type"content="text/html;......
  • JavaScript 前后切换图片
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <styletype="text/css"> *{ margin:0; padding:0; } #outer......
  • JavaScript 邮件的正则
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> /* *电子邮件 * hello.nihao......