java 纯nio使用 serverSocketChannel与socketChannel 最简单的例子,没有使用select,多线程等等

serverSocketChannel 是服务器端,监听端口,等待链接
Test2.java 是先监听端口,设置非阻塞,轮训seletor上的channel,根据channel的不同状态读取

运行main后,查看http头与body
curl -i 127.0.0.1:8080

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.UUID;

/**
 * @author zhanghui
 * @date 2019/6/28
 */
public class Test2 {

    public static void main(String[] args) {

        Selector selector = null;
        int port = 8080;
        try {
            selector = SelectorProvider.provider().openSelector();

            ServerSocketChannel serverChannel = SelectorProvider.provider().openServerSocketChannel();
            serverChannel.configureBlocking(false);
            serverChannel.bind(new InetSocketAddress("127.0.0.1", port));
            System.out.printf("Listen on port:"+port);
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);

            Test2.loopSelect(selector);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void loopSelect(Selector selector){

        while (true){
            //对socket异常处理,关闭
            SelectionKey selectionKey = null;
            try {
                int ready = selector.select();
                if (ready <= 0) continue;

                Iterator<SelectionKey> it = selector.selectedKeys().iterator();

                while(it.hasNext()){
                    selectionKey = it.next();

                    //不同类型处理,一个key可能是多个类型合集
                    if(selectionKey.isAcceptable()){
                        ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = serverChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.finishConnect();

                        Request request = new Request();
                        request.setSocketChannel(socketChannel);
                        request.setRequestId(UUID.randomUUID().toString());

                        SelectionKey key = socketChannel.register(selector,SelectionKey.OP_READ | SelectionKey.OP_WRITE); //http连接后,读写会同时就绪,保证先读
                        key.attach(request);

                    }
                    //ServerSocketChannel直接来读写了
                    if (!(selectionKey.channel() instanceof SocketChannel)){
                        it.remove();
                        continue;
                    }
                    if(selectionKey.isReadable()){
                        Request request = (Request) selectionKey.attachment();
                        SocketChannel socketChannel = request.getSocketChannel();
                        //循环读取,确定读取结束
                        ByteBuffer buf = ByteBuffer.allocate(1024);
                        int len = 0;
                        boolean readDone = false;
                        while (!readDone){
                            while((len = socketChannel.read(buf))>0){
                                buf.flip();
                                String tmp = new String(buf.array(),0,len);
                                System.out.println(tmp);
                                buf.clear();

                                //判断结束,get请求,末尾是两个换行
                                if(tmp.contains("\r\n\r\n")){
                                    readDone = true;
                                    break;
                                }
                            }
                        }

                        request.setReaded(true);
                        selectionKey.attach(request);
                    }
                    if(selectionKey.isWritable()){
                        Request request = (Request) selectionKey.attachment();
                        SocketChannel socketChannel = request.getSocketChannel();

                        //如果这个socketChannel还没有被先读
                        if(!request.isReaded()){
                            it.remove();
                            continue;
                        }

                        String sendStr = "Http/1.1 200 Ok\r\n" +
                                "Content-Type:text/html;charset=UTF-8\r\n" +
                                "\r\n" +
                                "<html><head><title>demo page</title></head><body>hi,world</body></html>";
                        ByteBuffer buf = ByteBuffer.wrap(sendStr.getBytes(StandardCharsets.UTF_8));
                        socketChannel.write(buf);

                        System.out.println("socket id:"+ request.getRequestId()+" done");
                        socketChannel.close();
                    }

                    it.remove();
                }

            } catch (IOException e) {
                e.printStackTrace();
                try {
                    selectionKey.channel().close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

//请求包装类
class Request{
    private SocketChannel socketChannel = null;
    private String requestId;
    private boolean readed = false;

    public SocketChannel getSocketChannel() {
        if(socketChannel == null)
            throw new RuntimeException("no socketChannel");
        return socketChannel;
    }

    public void setSocketChannel(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public boolean isReaded() {
        return readed;
    }

    public void setReaded(boolean readed) {
        this.readed = readed;
    }
}

socketChannel是连接服务使用,可以访问web服务器或做proxy代理服务

启动main后,控制台打印得到的http信息,现在很多都启用了全站https,所以很多都是返回302
和Test2.java过程类似,设置与开启selector轮训,然后根据channel的状态

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.UUID;

/**
 * @author zhanghui
 * @date 2019/6/26
 */
public class Test {


    public static void main(String[] args) {

        try {
            Selector selector = SelectorProvider.provider().openSelector();
//            String url = "ifeve.com";
//            int port = 80;
            String url = "127.0.0.1";
            int port = 8080;

            SocketChannel socketChannel = SelectorProvider.provider().openSocketChannel();
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress(url, port));
            socketChannel.register(selector,SelectionKey.OP_CONNECT);

            Test.loopSelect(selector);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void loopSelect(Selector selector){
        boolean isFinish = false;
        while (!isFinish) {
            try {
                int ready = selector.select();
                if (ready <= 0) continue;

                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();

                    if(selectionKey.isConnectable()){
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        if(socketChannel.finishConnect())
                        {
                            RequestTo requestTo = new RequestTo();
                            requestTo.setRequestId(UUID.randomUUID().toString());
                            requestTo.setSocketChannel(socketChannel);

                            SelectionKey selectionKey1 = socketChannel.register(selector,SelectionKey.OP_WRITE | SelectionKey.OP_READ);
                            selectionKey1.attach(requestTo);
                        }else{
                            throw new RuntimeException("connection failed");
                        }
                    }
                    if(selectionKey.isReadable()){
                        RequestTo requestTo = (RequestTo) selectionKey.attachment();
                        SocketChannel socketChannel = requestTo.getSocketChannel();

                        //未发送过请求
                        if(!requestTo.isWrited()){
                            it.remove();
                            continue;
                        }

                        int len = 0;
                        ByteBuffer buf = ByteBuffer.allocate(10240);
                        while ((len = socketChannel.read(buf)) != -1) {
                            buf.flip();
                            String tmp = new String(buf.array(),0,len);
                            System.out.println(tmp);
                            buf.clear();

                            //判断读取完毕, content-length, chunked, 等等,确定长度,比较复杂
                            break;
                        }
                        socketChannel.close();
                        return;
                    }
                    if(selectionKey.isWritable()){
                        RequestTo requestTo = (RequestTo) selectionKey.attachment();
                        SocketChannel socketChannel = requestTo.getSocketChannel();

                        String url = "ifeve.com";

                        String sendStr = "GET / HTTP/1.1\r\n" +
                                "Host: " + url + "\r\n" +
                                "\r\n";
                        ByteBuffer buf = ByteBuffer.wrap(sendStr.getBytes(StandardCharsets.UTF_8));


                        socketChannel.write(buf);

                        requestTo.setWrited(true);
                    }

                    it.remove();
                }
            } catch (IOException e) {
                e.printStackTrace();
                isFinish = true;
            }
        }
    }
}

class RequestTo{
    private SocketChannel socketChannel = null;
    private String requestId;
    private boolean writed = false;

    public SocketChannel getSocketChannel() {
        if(socketChannel == null)
            throw new RuntimeException("no socketChannel");
        return socketChannel;
    }

    public void setSocketChannel(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public boolean isWrited() {
        return writed;
    }

    public void setWrited(boolean writed) {
        this.writed = writed;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java NIO是一种用于高效处理I/O操作的Java API。其原理是在Java使用了一些新的I/O概念和类,包括缓冲区(Buffer)、通道(Channel)、选择器(Selector)等。 缓冲区是Java NIO中重要的概念之一,它是一个可以被读写的内存块,可以作为I/O操作的输入输出缓存。在Java NIO中,所有的数据读取和写入都必须通过缓冲区来完成。缓冲区分为直接缓冲区和非直接缓冲区两种。直接缓冲区是通过调用操作系统的API直接分配的内存块,可以显著提高I/O操作的性能;非直接缓冲区则是通过Java堆内存分配的,性能略逊于直接缓冲区。 通道是Java NIO中另一个重要的概念,它是一个用于传输数据的实体,可以读取和写入数据。通道提供了比Java传统的I/O流更高效的数据传输方式,因为它可以在缓冲区和底层操作系统之间建立直接的连接,避免了I/O流中的中间层。Java NIO中提供了多种类型的通道,包括文件通道、套接字通道等。 选择器是Java NIO中另一个重要的概念,它可以检测一个或多个通道的状态,并且可以在通道准备好进行读写操作时被通知。选择器提供了一种高效的方式来处理多个通道的I/O操作,可以避免线程阻塞和不必要的轮询。 综上所述,Java NIO通过使用缓冲区、通道和选择器等新的概念和类,可以提供更高效的I/O操作方式,可以在处理高并发和大数据量的情况下发挥出更好的性能。 ### 回答2: Java NIO(Non-blocking I/O) 是Java提供的一种新的I/O处理方式。相比于传统的I/O操作,Java NIO使用了非阻塞的方式来处理输入和输出。以下是Java NIO的主要原理: Java NIO主要包含以下几个核心组件: 1. Channel(通道):是用于读写数据的对象,可以理解为指向实际数据源的双向管道。不同类型的数据可以通过不同类型的通道进行传输。 2. Buffer(缓冲区):是一个用于存储数据的对象,实际上就是一个数组。数据通过缓冲区在通道和应用程序之间传输。 3. Selector(选择器):是一个可以监听多个通道事件的对象。可以通过Selector注册通道,并监听通道上的不同事件,如连接、接收和发送数据等。 Java NIO的工作流程如下: 1. 创建通道:使用Channel类创建需要的通道,如FileChannel、SocketChannelServerSocketChannel等。 2. 创建缓冲区:使用Buffer类创建需要的缓冲区,如ByteBuffer、CharBuffer等。 3. 将数据写入缓冲区:通过调用缓冲区的put()方法将数据写入缓冲区。 4. 切换缓冲区为读模式:通过调用缓冲区的flip()方法切换缓冲区为读模式。 5. 从缓冲区读取数据:通过调用缓冲区的get()方法从缓冲区读取数据。 6. 注册通道,并监听感兴趣的事件:通过Selector对象的register()方法注册通道,并指定感兴趣的事件,如连接就绪、接收就绪、写入就绪等。 7. 轮询选择器:通过Selector对象的select()方法进行轮询,查看是否有感兴趣的事件准备就绪。 8. 处理选择器就绪的事件:通过遍历SelectionKey集合,处理选择器返回的已就绪的事件。 9. 执行对应的操作:根据不同的事件类型,执行相应的操作,如连接、接收和发送数据等。 总结来说,Java NIO通过非阻塞的方式处理I/O操作,通过通道、缓冲区和选择器来实现高效的IO处理。它具有更高的处理能力、更低的内存消耗和更少的线程占用,适用于高并发、大数据量的应用场景。 ### 回答3: Java NIO(New I/O)是Java编程语言的一种扩展,提供了可以进行非阻塞I/O操作的功能。它是为了解决传统的阻塞I/O模型在高并发和大规模数据处理场景下性能不佳的问题而引入的。 Java NIO的核心概念是通道(Channel)和缓冲区(Buffer)。通道代表了一个可以进行读写操作的实体,提供了非阻塞的I/O操作。缓冲区是一个内存块,用于临时存储数据,供通道读写数据。 在Java NIO中,通过Selector可以同时监控多个通道的输入/输出状态。Selector会不断地轮询注册在其上的通道,如果某个通道发生了读或写事件,Selector就会将该通道加入到就绪集合中。这样,我们就可以通过Selector轮询检查哪些通道已经准备好进行读写,从而避免了传统阻塞I/O中每个连接需要一个线程等待数据的情况。 在Java NIO中,数据通过缓冲区进行传输。读取数据时,可以从通道读取数据到缓冲区中,然后从缓冲区中读取数据;写入数据时,可以将数据写入缓冲区,然后从缓冲区写入通道。通过使用缓冲区,可以减少实际的I/O操作次数,提高效率。 Java NIO还提供了FileChannel用于对文件进行I/O操作,以及SocketChannelServerSocketChannel用于对网络Socket进行I/O操作。此外,Java NIO还支持内存映射文件(Memory-mapped files),可以将文件直接映射到内存中,避免了传统文件I/O的开销。 总之,Java NIO通过通道、缓冲区和Selector等实现了高效的非阻塞I/O操作。相对于传统的阻塞I/O模型,可有效提高系统的并发处理能力和性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值