Netty簡單入門實例及代碼詳解

原文鏈接:http://www.youbiji.cn/user/hll/1568265752509.html

版權聲明,本文轉自:http://www.youbiji.cn/user/hll/1568265752509.html

本實例演示Netty服務端和客戶端如何傳遞消息,你只需要2分鐘就可以實現運行自己的第一個Netty程序。請複製粘貼下面的代碼到你的開發工具中看看效果吧!

添加maven依賴:

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.38.Final</version>
</dependency>

服務端消息處理類:
package com.demo.mynetty;

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

// 消息處理
public class ReceiveServerHandler extends ChannelInboundHandlerAdapter {

    // 收到消息時自動執行此方法
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 讀取消息
        ByteBuf buf = (ByteBuf)msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        ReferenceCountUtil.release(msg);
        String receivedMsg = new String(req, "UTF-8");
        System.out.println("服務器收到消息:" + receivedMsg);
        // 返回消息
        ByteBuf respBuf = Unpooled.copiedBuffer("服務器已收到消息".getBytes());
        ctx.write(respBuf);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

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

服務端:

package com.demo.mynetty;

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;

// 服務端
public class ReceiveServer {

    // 服務端配置
    public void bind(int port) throws Exception {
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();

        ServerBootstrap b = new ServerBootstrap();
        b.group(parentGroup, childGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ReceiveServerHandler());
            }
        });

        try {
            ChannelFuture f = b.bind(port).sync();
            // 阻塞直到服務端的鏈路關閉後優雅的退出
            f.channel().closeFuture().sync();
        } finally {
            // 釋放相關資源
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        new ReceiveServer().bind(20199);
    }

}

客戶端消息處理類:

package com.demo.mynetty;

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

// 消息處理
public class SendClientHandler extends ChannelInboundHandlerAdapter {

    // 收到消息時自動執行此方法
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 讀取消息
        ByteBuf buf = (ByteBuf)msg;
        byte[] resp = new byte[buf.readableBytes()];
        buf.readBytes(resp);
        // 釋放資源
        ReferenceCountUtil.release(msg);
        String respMsg = new String(resp, "UTF-8");
        System.out.println(respMsg);

    }

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

}

客戶端:

package com.demo.mynetty;

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;

// 客戶端
public class SendClient {

    // 和服務器建立連接
    public void connect(String host, int port) throws Exception {

        // 配置連接信息
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new SendClientHandler());
                }
            });
            // 建立連接
            ChannelFuture f = b.connect(host, port).sync();
            // 發送數據
            ByteBuf sendBuf = Unpooled.copiedBuffer("我是客戶端001".getBytes());
            f.channel().writeAndFlush(sendBuf);
            // 阻塞直到連接被關閉時優雅的退出
            f.channel().closeFuture().sync();
        } finally {
            // 釋放相關資源
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new SendClient().connect("127.0.0.1", 20199);
    }

}

最後先運行服務端main方法,再運行客戶端main方法查看效果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章