網路編程 -- RPC實現原理 -- Netty -- 迭代版本V3 -- 編碼解碼

來源:互聯網
上載者:User

標籤:style   pool   flush   worker   .net   sign   自動   lib   sage   

 網路編程 -- RPC實現原理 -- 目錄

  啦啦啦

V2——Netty -- pipeline.addLast(io.netty.handler.codec.MessageToMessageCodec<INBOUND_IN, OUTBOUND_IN>) 覆寫編碼解碼方法。

 pipeline相當於攔截器。在pipeline中添加MessageToMessageCodec介面的實作類別,該介面的實作類別中的encode()方法自動將發送的Object對象轉換為ByteBuf,decode()方法自動將接收的ByteBuf對象轉換為Object

 

  Class : Server

package lime.pri.limeNio.netty.netty03;import java.net.InetSocketAddress;import java.util.Date;import java.util.List;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.SerializerFeature;import io.netty.bootstrap.ServerBootstrap;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.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;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.MessageToMessageCodec;import io.netty.util.CharsetUtil;import lime.pri.limeNio.netty.netty03.entity.User;public class Server {    public static void main(String[] args) throws Exception {        ServerBootstrap serverBootstrap = new ServerBootstrap();        EventLoopGroup boss = new NioEventLoopGroup();        EventLoopGroup worker = new NioEventLoopGroup();        serverBootstrap.group(boss, worker);        serverBootstrap.channel(NioServerSocketChannel.class);        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {            @Override            protected void initChannel(SocketChannel ch) throws Exception {                ChannelPipeline pipeline = ch.pipeline();                pipeline.addLast(new MessageToMessageCodec<ByteBuf, Object>() {                    @Override                    protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {                        System.out.println("-- -- 服務端編碼");                        out.add(Unpooled.buffer().writeBytes(JSON.toJSONString(msg,SerializerFeature.WriteClassName).getBytes(CharsetUtil.UTF_8)));                    }                    @Override                    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {                        System.out.println("-- -- 服務端解碼");                        out.add(JSON.parse(msg.toString(CharsetUtil.UTF_8)));                    }                }).addLast(new ChannelHandlerAdapter() {                    @Override                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {                        System.out.println("用戶端請求資料:" + msg);                        String request = (String) msg;                        Object response = "請求參數不正確";                        if("Query Date".equalsIgnoreCase(request)){                            response = "當前系統時間:" + new Date().toString();                        }else if("Query User".equalsIgnoreCase(request)){                            response = new User(1,"lime",new Date());                        }                        ChannelFuture channelFuture = ctx.writeAndFlush(response);                        channelFuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);                        channelFuture.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);                        channelFuture.addListener(ChannelFutureListener.CLOSE);                    }                    @Override                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {                        cause.printStackTrace();                    }                });            }        });        ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(9999)).sync();        channelFuture.channel().closeFuture().sync();        boss.close();        worker.close();    }}

  Class : Client

package lime.pri.limeNio.netty.netty03;import java.net.InetSocketAddress;import java.util.List;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.SerializerFeature;import io.netty.bootstrap.Bootstrap;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.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;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.MessageToMessageCodec;import io.netty.util.CharsetUtil;public class Client {    public static void main(String[] args) throws Exception {        for (int i = 0; i < 10; i++) {            new Thread() {                {                    setDaemon(false);                }                public void run() {                    try {                        client();                    } catch (Exception e) {                        e.printStackTrace();                    }                };            }.start();            Thread.sleep(1000);        }    }    private static void client() throws Exception {        Bootstrap bootstrap = new Bootstrap();        EventLoopGroup worker = new NioEventLoopGroup();        bootstrap.group(worker);        bootstrap.channel(NioSocketChannel.class);        bootstrap.handler(new ChannelInitializer<SocketChannel>() {            @Override            protected void initChannel(SocketChannel ch) throws Exception {                ChannelPipeline pipeline = ch.pipeline();                pipeline.addLast(new MessageToMessageCodec<ByteBuf, Object>() {                    @Override                    protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {                        System.out.println("-- -- 用戶端編碼");                        out.add(Unpooled.buffer().writeBytes(JSON.toJSONString(msg, SerializerFeature.WriteClassName).getBytes(CharsetUtil.UTF_8)));                    }                    @Override                    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {                        System.out.println("-- -- 用戶端解碼");                        out.add(JSON.parse(msg.toString(CharsetUtil.UTF_8)));                    }                }).addLast(new ChannelHandlerAdapter() {                    /**                     * 預設只捕獲網路連接異常                     */                    @Override                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {                        System.out.println(cause);                    }                    /**                     * 用戶端發送經過JSON編碼的byteBuf                     */                    @Override                    public void channelActive(ChannelHandlerContext ctx) throws Exception {                        String request = null;                        switch ((int) (Math.random() * 10) % 3) {                        case 0:                            request = "Query Date";                            break;                        case 1:                            request = "Query User";                            break;                        default:                            request = "Query What?";                            break;                        }                        ChannelFuture channelFuture = ctx.writeAndFlush(request);                        channelFuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);                        channelFuture.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);                    }                    @Override                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {                        System.out.println("服務端響應資料 --> " + msg);                    }                });            }        });        ChannelFuture channelFuture;        channelFuture = bootstrap.connect(new InetSocketAddress(9999)).sync();        channelFuture.channel().closeFuture().sync();        worker.close();    }}

啦啦啦

網路編程 -- RPC實現原理 -- Netty -- 迭代版本V3 -- 編碼解碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.