NIO模型实现

单线程NIO

我们先实现单线程的NIO,我们后面把它改成多线程。
如果要实现NIO的网络模型,我们就需要三大组件:Selector,Channel,ByteBuffer
Selector : 用来监听Channel上的某种事件
Channel:一个服务器对应一个Channel,也就是一个管道。
ByteBuffer:指的是字节缓冲区,我们要把数据流读取到ByteBuffer中才能获取并处理它,或者把数据写入ByteBuffer中,才可以将它发送到网络中去。
SelectionKey用来表示事件,还可以表示事件的类型。

好我们来详细说一下实现的流程
服务端:
首先对三大组件要初始化以及port的设置,把ServerSocketChannel管道置为非阻塞状态,并且注册到Selector中,去监听连接事件。

创建一个监听的方法(Listener),监听管道(ServerSocketChannel)发生的事件,如果发生了某种事件,把selector中的监听到的事件放入一个Set集合中,遍历Set集合,把事件处理,删除处理完的事件。

创建一个处理事件的方法(Handle),对事件进行分类判断,如果连接事件(服务器对应的连接事件是accept),那么就把把对应的管道注册到Selctor中去监听这个管道的读事件(也就是客户端个有消息发送给服务端);如果是读事件那么就把发生事件的对应管道的数据读取到ByteBuffer中,然后给服务器进行回复,也就是写事件,写完之后,先把数据放到ByteBuffer中,再把让管道把ByteBuffer写入。这样客户端就能收到消息了。

客户端:
与服务端基本一致,唯一不同的就是监听管道是SocketChannel,监听的连接事件是Connectable,当监听到连接时间时,要判断三次握手是否完成,所以要调用管道的isConnectionPending()方法如果返回为真,就调用管道的finishedConnect()方法完成连接。其余都相同。

这种单线程实现的NIO模式叫做Reactor模式
在这里插入图片描述

具体实现:
客户端:

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.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class NIOSingletestCilent {
   
    //服务端的端口号
    private int port = 1234;
    //三大组件selector channel Bytebuffer
    private Selector selector;
    private SocketChannel socketChannel ;
    private ByteBuffer rcveBuffer;
    private ByteBuffer sendBuffer;
    private Scanner scanner;
    //结构体初始化
    public NIOSingletestCilent() throws IOException {
   
        selector  = Selector.open();
        socketChannel = SocketChannel.open();
        rcveBuffer = ByteBuffer.allocate(1024);
        sendBuffer = ByteBuffer.allocate(1024);
        //把管道置为阻塞,并且把管道注册到selector
        socketChannel.configureBlocking(false);
        //设置与哪一个ip的哪一个port建立连接
        socketChannel.connect(new InetSocketAddress("127.0.0.1",port));
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        scanner = new Scanner(System.in);
    }
    //监听事件
    public void listener() throws IOException {
   
        while(true){
   
            int selcet = selector.selectNow();
            //如果有事件,那么就读取到Set集合上,并处理后删除。
            if(selcet > 0 ){
   
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                if(selectionKeys.isEmpty()) continue;
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while(iterator.hasNext()){
   
                    SelectionKey clientEvent = iterator.next();
                    handle(clientEvent);
                    iterator.remove();
                }
            }
        }
    }

    //处理事件
    private void handle (SelectionKey selectionKey)  {
   
        try {
   
            if (selectionKey.isValid()) {
   
                //如果事件是连接请求事件
                if (selectionKey.isConnectable()) {
   
                    System.out.println("正在连接服务器");
                    //如果已经完成了三次握手,那么就完成连接
                    if (socketChannel.isConnectionPending()) {
   
                        socketChannel.finishConnect();
                        System.out.println("连接成功");
                    }
                    //将读事件添加到selector中去。
                    sendMessage((SocketChannel) selectionKey.channel());
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    //如果是读事件
                } else if (selectionKey.isReadable()) {
   
                    rcveBuffer.clear();
                    int read = socketChannel.read(rcveBuffer);
                    if(read > 0) {
   
                        String rev = new String(rcveBuffer.array(), 0, read);
                        System.out.println("服务器的消息为:" + rev);
                    }
                    sendMessage((SocketChannel) selectionKey.channel());
                }
            }
        }catch(IOException e){
   
            if(e.getMessage().equals("远程主机强制关闭了一个连接")){
   
                System.out.println("关闭连接");
                try {
   
                    selector.close();
                    socketChannel.close();
                } catch (IOException e1) {
   
                    e1.printStackTrace();
                }

            }

        }
    }
    //发送消息
    public void sendMessage(SocketChannel socketChannel ) throws IOException {
   
        sendBuffer.clear();
        System.out.println("请输入字符");
        //读取控制台的输入字符
        String send = scanner.next();
        //将字符添加到sendBuffer中去写后发送消息并将指针移动到最开始的为止
        sendBuffer.put(send.getBytes());
        sendBuffer.flip();
        socketChannel.write(sendBuffer);

    }

    public static void main(String[] args) {
   
        try {
   
             NIOSingletestCilent nioSingletestCilent = new NIOSingletestCilent();
            nioSingletestCilent.listener();
        } catch (IOException e) {
   
            e.printStackTrace();
        }
    }
}

服务端:

public class NIOsingletestSerever {
   
    //服务器端口号
    private int port = 1234;
    //三大组件,selector,channel,buffer;
    Selector selector;
    ServerSocketChannel serverSocketChannel;
    ByteBuffer rev;
    ByteBuffer send;

    NIOsingletestSerever() throws IOException {
   
        selector = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        rev = ByteBuffer.allocate(1024);
        send = ByteBuffer.allocate(1024);
        //置为非阻塞状态
        serverSocketChannel.configureBlocking(false);
        //绑定端口号
        serverSocketChannel.bind(new
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值