netty4基本配置

本文介绍了Netty4.1.31的基本配置,包括服务端和客户端的实现。强调了数据处理部分、超时处理的设置。特别提醒,在启动服务端时不要去掉`sync()`并注释相关代码,否则会导致服务器关闭。此外,Netty4默认使用字节进行数据传输,若要发送字符串,需使用StringEncoder进行编码,或者将byte[]转换为ByteBuf进行发送。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

netty 4.1.31

服务端代码

import com.crane.mudal.project.socket.WebsocketServer;
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;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.boot.ApplicationArguments;

import java.util.concurrent.TimeUnit;

public class NettyServer {
    private static final int port = 3000;
    public void run() throws Exception{
        //NioEventLoopGroup是用来处理IO操作的多线程事件循环器
        EventLoopGroup bossGroup  = new NioEventLoopGroup();  // 用来接收进来的连接
        EventLoopGroup workerGroup  = new NioEventLoopGroup();// 用来处理已经被接收的连接
        try{
            ServerBootstrap server =new ServerBootstrap();//是一个启动NIO服务的辅助启动类
            server.group(bossGroup,workerGroup )
                    .channel(NioServerSocketChannel.class)  // 这里告诉Channel如何接收新的连接
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 自定义处理类
                            ch.pipeline().addLast(new IdleStateHandler(31,0,0, TimeUnit.SECONDS));
                            ch.pipeline().addLast(new IdleStateTrigger());
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            server.option(ChannelOption.SO_BACKLOG,1024);
            server.childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = server.bind(port);// 绑定端口,开始接收进来的连接
            System.out.println("服务端启动成功...");
            // 监听服务器关闭监听
            f.channel().closeFuture();
        }finally {
//            bossGroup.shutdownGracefully(); 关闭EventLoopGroup,释放掉所有资源包括创建的线程
//            workerGroup.shutdownGracefully();
        }

        // 服务器绑定端口监听


    }

 数据处理部分

import com.alibaba.fastjson.JSONArray;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.ReferenceCountUtil;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.util.Date;

@Component
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    //收到数据时调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf in = (ByteBuf) msg;
            int readableBytes = in.readableBytes();
            byte[] bytes = new byte[readableBytes];
            in.readBytes(bytes);
            
        } finally {
            // 抛弃收到的数据
            ReferenceCountUtil.release(msg);
        }
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
        logger.error("connection断开:" + ctx.channel().remoteAddress());
    }

    /*
     * 建立连接时,返回消息
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接的客户端地址:" + ctx.channel().remoteAddress());
        ctx.writeAndFlush("client" + InetAddress.getLocalHost().getHostName() + "success connected! \n");
        super.channelActive(ctx);
    }


}

超时处理

package com.crane.mudal.project.netty;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;


@ChannelHandler.Sharable
public class IdleStateTrigger extends ChannelInboundHandlerAdapter {
    private Log logger = LogFactory.getLog(IdleStateTrigger.class);
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
                ctx.channel().close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}

客户端


import com.crane.mudal.project.utils.Crc;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class HeartBeatClient {

    int port = 3000;
    Channel channel;



    public static void run() throws Exception {
        heartBeatClient.start();
    }

    public void start() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new HeartBeatClientInitializer());

            connect(bootstrap, port);
            String text = "www.usr.cn";
            while (channel.isActive()) {
                sendMsg(text);
            }
        } catch (Exception e) {
            // do something
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public void connect(Bootstrap bootstrap, int port) throws Exception {
        channel = bootstrap.connect("localhost", 3000).sync().channel();
    }

    public void sendMsg(String text) throws Exception {
        int num = 30;
        Thread.sleep(num * 1000);
        channel.writeAndFlush(text);
    }

    static class HeartBeatClientInitializer extends ChannelInitializer<Channel> {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("decoder", new StringDecoder());
            pipeline.addLast("encoder", new StringEncoder());
            pipeline.addLast(new HeartBeatClientHandler());
        }
    }

    static class HeartBeatClientHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println(" client received :" + msg);
            if (msg != null && msg.equals("you are out")) {
                System.out.println(" server closed connection , so client will close too");
                ctx.channel().closeFuture();
            }
        }
    }
    @Scheduled(initialDelay = 3000,fixedRate = 36000000)
    public void Tasks() throws InterruptedException {
        
    }
}

基本上就是这些代码,netty4用起来还不错没有明显的坑。只有一点值得注意在启动服务端的时候把sync()去掉后,不把

bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();

注释掉。会关闭服务器

netty4向client发送数据时,默认编码为字节,如果encode和decode定义为new StringEncoder()这类则发送字符串。

默认时要发送ByteBuf,通过ByteBuf buf = Unpooled.wrappedBuffer(msgByte);将byte[]转为ByteBuf,然后发送。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值