nio

概述

    nio故名思意为非阻塞型io但是在java中nio其实并非如此 在java中nio设计的模式为异步阻塞模型也叫reactor模型

介绍

    nio主要由三个部分组成 selector, channel ,buffer . select 通过select方法阻塞监听channe的读写l事件 channel通过buffer将读取的信息写入buffer中去或者通过buffer中的信息将该信息写入目标区域中。

大致运行流程

selector通过阻塞的方法select()监听事件 当有事件请求进行io操作的时候则由channel进行相应的读写事件 

channel读取或者要写入的事件通过buffer进行硬盘的写入或者读取数据的存放。

示例

package com.xiao.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
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.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class NioServer {
    private static Map<String,SocketChannel> clientMap =new HashMap<>();
    public static void main(String args[]) throws IOException{
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        ServerSocket serverSocket=serverSocketChannel.socket();
        InetSocketAddress socketAddress=new InetSocketAddress(8899);
        serverSocket.bind(socketAddress);
        Selector selector=Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true){
            try {
                selector.select();
                Set<SelectionKey> selectionKeys=selector.selectedKeys();
                selectionKeys.forEach(selectionKey -> {
                    try {
                        final SocketChannel client;
                        if (selectionKey.isAcceptable()){

                            ServerSocketChannel serverSocketChannel1=(ServerSocketChannel) selectionKey.channel();
                            client=serverSocketChannel.accept();
                            client.configureBlocking(false);
                            client.register(selector,SelectionKey.OP_READ);
                            String key="["+ UUID.randomUUID()+"]";
                            clientMap.put(key,client);

                        }else if (selectionKey.isReadable()){
                            client=(SocketChannel) selectionKey.channel();
                            ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                            int count=client.read(byteBuffer);
                            if (count>0){
                                byteBuffer.flip();
                                Charset charset=Charset.forName("UTF-8");
                                String receivemsg=String.valueOf(charset.decode(byteBuffer).array());
                                System.out.println("msg: "+receivemsg);
                                String sendkey=null;
                                for (Map.Entry<String,SocketChannel>entry :clientMap.entrySet() ){
                                    if (client==entry.getValue()){
                                        sendkey=entry.getKey();
                                        break;
                                    }

                                }
                                for (Map.Entry<String,SocketChannel>entry :clientMap.entrySet()){
                                    SocketChannel socketChannel=entry.getValue();
                                    ByteBuffer byteBuffer1=ByteBuffer.allocate(1024);
                                    byteBuffer1.put(( sendkey+":"+receivemsg).getBytes());
                                    byteBuffer.flip();
                                    socketChannel.write(byteBuffer);
                                }
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                });
                selectionKeys.clear();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值