天天看點

BIO,NIO,Netty代碼實作

BIO:同步阻塞式程式設計,同一個線程隻能處理一個用戶端請求。

代碼實作如下(本地可以通過Telnet充當用戶端+debug斷點測試功能):

package io;


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


/**
* 阻塞IO
*/
public class BioServerDemo {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9000);
        while(true){
            System.out.println("等待連接配接。。");
//            阻塞方法
//            telnet localhost 9000
//            CTRL+]進入Telnet指令
            Socket clientSocket = serverSocket.accept();
            System.out.println("有用戶端連接配接了。。");
//            雖然采用多線程可以支援多個線程同時通路,但是會引發C10K問題
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
                        handler(clientSocket);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }).start();
        }
    }


    private static void handler(Socket clientSocket) throws IOException {
        byte[] bytes = new byte[1024];
        System.out.println("準備read。。");
//        接收用戶端的資料,阻塞方法,沒有資料可讀時就阻塞
        int read  = clientSocket.getInputStream().read(bytes);
        System.out.println("read完畢。。");
        if (read !=-1){
            System.out.println("接收用戶端的資料:"+new String(bytes,0,read));
        }
//        clientSocket.getOutputStream().write("HelloClint".getBytes(StandardCharsets.UTF_8));
//        clientSocket.getOutputStream().flush();
    }
}
           

telnet指令(建議開兩個看效果):telnet localhost 9000(連接配接後CTRL+]進入Telnet指令)

BIO,NIO,Netty代碼實作

控制台輸出:

BIO,NIO,Netty代碼實作

 NIO:同步非阻塞,同一個線程可以處理多個用戶端請求。 

BIO,NIO,Netty代碼實作

 代碼實作:

package io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *初版- NIO(非阻塞)程式設計
 */
public class NioServer {
    static List<SocketChannel> channelList = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
        serverSocketChannel.configureBlocking(false);
        System.out.println("服務啟動成功");
        while (true){
            SocketChannel socketChannel = serverSocketChannel.accept();
           if(socketChannel!=null){
               System.out.println("連接配接成功");
               socketChannel.configureBlocking(false);
               channelList.add(socketChannel);
           }
//     問題點: 空循環時間耗時太久
           Iterator<SocketChannel> iterator = channelList.iterator();
           while (iterator.hasNext()){
               SocketChannel sc = iterator.next();
               ByteBuffer byteBuffer = ByteBuffer.allocate(128);
               int len = sc.read(byteBuffer);
               if (len>0){
                   System.out.println("接收到消息:"+new String(byteBuffer.array()));
               }else if(len ==-1){
                   iterator.remove();
                   System.out.println("用戶端斷開連接配接");
               }
           }
        }
    }
}
           
package io;

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.util.Iterator;
import java.util.Set;
/**
 *進階版- NIO(非阻塞)程式設計
 * 這是netty和Redis的雛形
 */
public class NioSelectorServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
        serverSocketChannel.configureBlocking(false);
//       啟用epoll模型
        Selector selector = Selector.open();
//        注冊阻塞事件:建立連接配接
        SelectionKey selectionKey = serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
        System.out.println("服務啟動成功");
        while (true){
//            阻塞等待需要處理的事件發生,這個時候是等待連接配接
            selector.select();
//            擷取阻塞的事件
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
//            對阻塞事件進行周遊
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            if(iterator.hasNext()){
                SelectionKey key =iterator.next();
                if(key.isAcceptable()){//連接配接已建立
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = server.accept();
                    socketChannel.configureBlocking(false);
                    //        注冊阻塞事件:讀取資料
                    SelectionKey selKey = socketChannel.register(selector,SelectionKey.OP_READ);
                }else if(key.isReadable()){//這裡隻針對read事件,有需要可以針對write事件處理
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                    socketChannel.configureBlocking(false);
                    int len  = socketChannel.read(byteBuffer);
                    if(len >0 ){
                        System.out.println("接收到消息:"+new String(byteBuffer.array()));
                    }else if(len ==-1 ){
//                       關閉socket
                        socketChannel.close();
                        System.out.println("接收完成");
                    }
                }
//                把處理完的阻塞事件移除
                iterator.remove();
            }

        }
    }
}
           

Telnet如圖:

BIO,NIO,Netty代碼實作
BIO,NIO,Netty代碼實作

 控制台輸出:

BIO,NIO,Netty代碼實作

 netty:可以了解成在NIO的selector版本上進行了封裝

代碼實作:

package io.netty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


/**
* netty 服務端
*/
public class NettyServer {
    public static void main(String[] args)  {
        // 我們要建立兩個EventLoopGroup,
        // 一個是boss專門用來接收連接配接,可以了解為處理accept事件,
        // 另一個是worker,可以關注除了accept之外的其它事件,處理子任務。
        //上面注意,boss線程一般設定一個線程,設定多個也隻會用到一個,而且多個目前沒有應用場景,
        // worker線程通常要根據伺服器調優,如果不寫預設就是cpu的兩倍。
        //boss注冊accept事件
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
//        worker注冊其他事件
        EventLoopGroup workerGroup = new NioEventLoopGroup(8);
        //服務端要啟動,需要建立ServerBootStrap,
        // 在這裡面netty把nio的模闆式的代碼都給封裝好了
           ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            //配置boss和worker線程
        bootstrap.group(bossGroup,workerGroup)
                //配置Server的通道,相當于NIO中的ServerSocketChannel
                .channel(NioServerSocketChannel.class)
                //初始化伺服器連接配接隊列大小,服務端處理用戶端連接配接請求是順利處理的,是以同一個事件隻能處理一個用戶端連接配接。
//                多個用戶端同時來的時候,服務端将不能處理的用戶端連接配接請求放在隊列中等待處理。
                .option(ChannelOption.SO_BACKLOG,1024)
                //childHandler表示給worker那些線程配置了一個處理器,
                // 配置初始化channel,也就是給worker線程配置對應的handler,當收到用戶端的請求時,配置設定給指定的handler處理
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyServerHandler());//添加handler,也就是具體的IO事件處理器
                    }
                });
        System.out.println("netty server start ..");
            //由于預設情況下是NIO異步非阻塞,是以綁定端口後,通過sync()方法阻塞直到連接配接建立
            //綁定端口并同步等待用戶端連接配接(sync方法會阻塞,直到整個啟動過程完成)
        ChannelFuture cf = bootstrap.bind(9000).sync();
//等待服務端監聽端口關閉
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //釋放線程資源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}
           
package io.netty;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;


/**
* 服務端ChannelHandler處理類
*/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("用戶端連接配接通道建立完成");
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("收到用戶端的消息:"+buf.toString(CharsetUtil.UTF_8));
    }
}
           
package io.netty;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* @description:netty用戶端
* @author: zhoufanshou
* @date: 2022/8/8 14:32
**/
public class NettyClient {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new NettyClientHandler());//增加處理類
                    }
                });
            System.out.println("netty client start..");
            ChannelFuture cf = bootstrap.connect("127.0.0.1",9000);
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
}

package io.netty;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledDirectByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;


import java.nio.charset.StandardCharsets;
/**
* @description:用戶端ChannelHandler處理類
* @author: zhoufanshou
* @date: 2022/8/8 14:29
**/
public class NettyClientHandler extends ChannelInboundHandlerAdapter   {
    /**
     * @description:
     * @author: zhoufanshou
     * @date: 2022/8/8 14:22
     * @param:   ctx
     * @return:
    **/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer("helloworld".getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(buf);
    }
/**
* @description:
* @author: zhoufanshou
* @date: 2022/8/8 14:22
* @param:   ctx,  msg
* @return:
**/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("用戶端收到資訊:"+buf.toString(CharsetUtil.UTF_8));
    }
}
           

控制台輸出:

首先設定idea用戶端多執行個體運作:

BIO,NIO,Netty代碼實作

輸出結果(打開兩個用戶端的效果)如下:

BIO,NIO,Netty代碼實作