1. 程式人生 > >網際網路技術20——netty入門

網際網路技術20——netty入門

Socket網路通訊程式設計--Netty

Netty是一個提供非同步事件驅動的網路應用框架,用以快速開發高效能、高可靠性的網路伺服器和客戶端程式。

換句話說,Netty是一個NIO框架,使用它可以簡單快速的開發網路應用程式,比如客戶端和服務端的協議。Netty大大簡化了網路程式的開發過程中比如TCP和UDP的Socket開發。

“快速和簡單”並不意味著應用程式會有難維護和低效能的問題,Netty是一個精心設計的框架,它從許多協議的實現中吸收了很多經驗比如FTP、SMTP、HTTP、許多二進位制基於文字的傳統協議,Netty在不降低開發效率、效能、穩定性、靈活性的情況下,成功的找到了解決方案。

使用者指南:http://ifeve.com/netty5-user-guide/

簡單應用

server.java

package com.nettyTest;


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.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by BaiTianShi on 2018/9/5.
 */
public class Server {

    private int port;

    public Server(int port) {
        this.port = port;
    }

    public void run() {
        //用來接收連線事件組
        EventLoopGroup boss = new NioEventLoopGroup();
        //用來處理接收到的連線事件處理組
        EventLoopGroup worker = new NioEventLoopGroup();
        //server配置輔助類
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {

            //將連線接收組與事件處理組連線,當server的boss接收到連線收就會交給worker處理
            bootstrap.group(boss, worker)
                    //指定channel型別
                    .channel(NioServerSocketChannel.class)
                    //handler會在初始化時就執行,而childHandler會在客戶端成功connect後才執行
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ServerHandler());
                        }
                    })
                    //設定tcp緩衝區大小
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //設定傳送緩衝區大小
                    .option(ChannelOption.SO_SNDBUF, 1024 * 32)
                    //設定接收緩衝區大小
                    .option(ChannelOption.SO_RCVBUF, 1024 * 32)
                    //設定是否儲存長連線
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            //注意。此處option()是提供給NioServerSocketChannel用來接收進來的連線,也就是boss執行緒
            //childOption是提供給有福管道serverChannel接收到的連線,也就是worker執行緒,在這個例子中也就是NioServerSocketChannel


            //非同步繫結埠,可以繫結多個埠
            ChannelFuture fu1 = bootstrap.bind(port).sync();
            ChannelFuture fu2 = bootstrap.bind(8766).sync();

            //非同步檢查是否關閉
            fu1.channel().closeFuture().sync();
            fu2.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        Server server = new Server(8765);
        server.run();
    }
}

ServerHandler.java

package com.nettyTest;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by BaiTianShi on 2018/9/5.
 */
public class ServerHandler extends ChannelHandlerAdapter {
    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
        System.out.println("Exception Caught...");
        super.exceptionCaught(channelHandlerContext, throwable);
    }

    @Override
    public void channelRead(final ChannelHandlerContext channelHandlerContext, Object o) throws Exception {

        try {

            ByteBuf buf = (ByteBuf) o;
            byte[] bt = new byte[buf.readableBytes()];
            buf.readBytes(bt);
            System.out.println("服務端接收到客戶端請求:"+ new String(bt,"utf-8"));

            ChannelFuture fu = channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer(("hi client").getBytes()));
            fu.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    System.out.println("服務端監聽到資料反饋傳送完畢");
                    channelHandlerContext.close();
                }
            });
            fu.addListener(ChannelFutureListener.CLOSE);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//        write方法會自動釋放,write後不是必須執行此方法,只有read方法後執行此方法
            ReferenceCountUtil.release(channelHandlerContext);
        }

    }
}

Client.java

package com.nettyTest;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
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.NioSocketChannel;

/**
 * Created by BaiTianShi on 2018/9/5.
 */
public class Client {

    private String ip;
    private int port;

    public Client(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }


    public void run(){
        //客戶端用來連線服務端的連線組
        EventLoopGroup worker= new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ClientHandler());
                    }
                })
                .option(ChannelOption.SO_KEEPALIVE,true);


        try {
            //可以進多個埠同時連線
            ChannelFuture fu1 = bootstrap.connect(ip,port).sync();
            ChannelFuture fu2 = bootstrap.connect(ip,8766).sync();

            fu1.channel().writeAndFlush(Unpooled.copiedBuffer( ("Hello Server").getBytes()));
            fu2.channel().writeAndFlush(Unpooled.copiedBuffer( ("Hello Server8766").getBytes()));

            fu1.channel().closeFuture().sync();
            fu2.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        Client cl = new Client("127.0.0.1",8765);
        cl.run();
    }
}

ClientHandler.java

package com.nettyTest;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by BaiTianShi on 2018/9/5.
 */
public class ClientHandler extends ChannelHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            System.out.println("客戶端接收反饋資料:" + new String(bytes,"utf-8"));
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}

server端控制檯

client端控制檯

 

 

 

建立Netty通訊服務的四個步驟:

1. 建立2個NIO執行緒組,一個專門用於網路時間處理(接收客戶端的連線),另一個則進行網路通訊讀寫

2. 建立一個ServerBootStrap物件,配置Netty的一系列引數,例如接收傳出資料的快取大小等

3. 建立一個實際處理資料的類ChannelInitializer,進行初始化的準備工作,比如設定接收或傳出資料的字符集、格式、以及實際處理資料的埠

4. 繫結埠,執行同步阻塞方法等待伺服器端啟動即可。

 

在netty中,預設傳輸都輸ByteBuf型別的,如果要以其他型別的格式,必須在配置ChanneIlnitializer的時候,需要配置影響的編碼器和解碼器(netty已經提供)。注意配置的時候服務端和客戶端最好都要配置,否則沒有配置的一方獲取的還是ByteBuf。這裡的演示程式碼只配置了server端,有興趣的可以按照server自己去配置一下client端

package com.nettyString;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Created by BaiTianShi on 2018/9/5.
 */
public class Server {

    private int port;

    public Server(int port) {
        this.port = port;
    }

    public void run() {
        //用來接收連線事件組
        EventLoopGroup boss = new NioEventLoopGroup();
        //用來處理接收到的連線事件處理組
        EventLoopGroup worker = new NioEventLoopGroup();
        //server配置輔助類
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {

            //將連線接收組與事件處理組連線,當server的boss接收到連線收就會交給worker處理
            bootstrap.group(boss, worker)
                    //指定channel型別
                    .channel(NioServerSocketChannel.class)
                    //handler會在初始化時就執行,而childHandler會在客戶端成功connect後才執行
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ByteBuf byteBuf = Unpooled.copiedBuffer("$_".getBytes());
                            socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,byteBuf));
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new StringEncoder());
                            socketChannel.pipeline().addLast(new ServerHandler());
                        }
                    })
                    //設定tcp緩衝區大小
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //設定傳送緩衝區大小
                    .option(ChannelOption.SO_SNDBUF, 1024 * 32)
                    //設定接收緩衝區大小
                    .option(ChannelOption.SO_RCVBUF, 1024 * 32)
                    //設定是否儲存長連線
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            //注意。此處option()是提供給NioServerSocketChannel用來接收進來的連線,也就是boss執行緒
            //childOption是提供給有福管道serverChannel接收到的連線,也就是worker執行緒,在這個例子中也就是NioServerSocketChannel


            //非同步繫結埠,可以繫結多個埠
            ChannelFuture fu1 = bootstrap.bind(port).sync();
            ChannelFuture fu2 = bootstrap.bind(8766).sync();

            //非同步檢查是否關閉
            fu1.channel().closeFuture().sync();
            fu2.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        Server server = new Server(8765);
        server.run();
    }
}

 

serverHandler

package com.nettyString;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by BaiTianShi on 2018/9/5.
 */
public class ServerHandler extends ChannelHandlerAdapter {
    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
        System.out.println("Exception Caught...");
        super.exceptionCaught(channelHandlerContext, throwable);
    }

    @Override
    public void channelRead(final ChannelHandlerContext channelHandlerContext, Object o) throws Exception {

        try {
            System.out.println("收到");
            String str = (String) o;
            System.out.println("服務端接收到客戶端請求:"+str);

            ChannelFuture fu = channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer(("hi client").getBytes()));
            fu.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    System.out.println("服務端監聽到資料反饋傳送完畢");
                    channelHandlerContext.close();
                }
            });
            fu.addListener(ChannelFutureListener.CLOSE);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(channelHandlerContext);
        }

    }
}

client

package com.nettyString;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
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.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Created by BaiTianShi on 2018/9/5.
 */
public class Client {

    private String ip;
    private int port;

    public Client(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }


    public void run(){
        //客戶端用來連線服務端的連線組
        EventLoopGroup worker= new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ByteBuf byteBuf = Unpooled.copiedBuffer("$_".getBytes());
                        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,byteBuf));
                        socketChannel.pipeline().addLast(new StringDecoder());
                        socketChannel.pipeline().addLast(new StringEncoder());
                        socketChannel.pipeline().addLast(new ServerHandler());
                        socketChannel.pipeline().addLast(new ClientHandler());
                    }
                })
                .option(ChannelOption.SO_KEEPALIVE,true);


        try {
            //可以進多個埠同時連線
            ChannelFuture fu1 = bootstrap.connect(ip,port).sync();
            ChannelFuture fu2 = bootstrap.connect(ip,8766).sync();

            fu1.channel().writeAndFlush("Hello Server$_");
            fu2.channel().writeAndFlush(Unpooled.copiedBuffer( ("Hello Server8766").getBytes()));

            fu1.channel().closeFuture().sync();
            fu2.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        Client cl = new Client("127.0.0.1",8765);
        cl.run();
    }
}

 

clientHandler

package com.nettyString;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by BaiTianShi on 2018/9/5.
 */
public class ClientHandler extends ChannelHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);
            System.out.println("客戶端接收反饋資料:" + new String(bytes,"utf-8"));
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}