Netty 服务端,接受信息,且返回状态

 <!-- netty -->
  <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-all</artifactId>
      <version>4.1.12.Final</version>
  </dependency>
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class NettyServer {

    private static final int port = 9091;

    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 NettyServerHandler());
                        }
                    });
            // 具体参数介绍 https://blog.csdn.net/zhousenshan/article/details/72859923
            server.option(ChannelOption.SO_BACKLOG,128);
            // 保持长连接
            server.childOption(ChannelOption.SO_KEEPALIVE, true);
            //绑定端口,同步等待成功
            ChannelFuture future = server.bind(port).sync();
            log.info("服务端启动成功...");
            // 监听服务器关闭监听
            future.channel().closeFuture().sync();
        }finally {
            //关闭EventLoopGroup,释放掉所有资源包括创建的线程
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        new NettyServer().run();
    }
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

@Slf4j
@Component
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 收到数据时调用
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @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);
            String str = new String(bytes);
            //System.out.print(in.toString(CharsetUtil.UTF_8));
            log.info("服务端接受的消息 : " + str);
            log.info("服务端接受的消息 : " + msg);
        }finally {
            // 抛弃收到的数据
            ReferenceCountUtil.release(msg);
        }
    }

    /**
     * 数据读取完毕事件
     * @param ctx
     */
    public void channelReadComplete(ChannelHandlerContext ctx){
         //数据读取完毕,将信息包装成一个Buffer传递给下一个Handler,Unpooled.copiedBuffer会返回一个Buffer
         //调用的是事件处理器的上下文对象的writeAndFlush方法
         //意思就是说将  *参数*  传递给了下一个handler
        ByteBuf byteBuf = Unpooled.copiedBuffer("Receive the success ", CharsetUtil.UTF_8);
        ctx.writeAndFlush(byteBuf);
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     */
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        try{
            cause.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
            log.error("异常.."+e.getMessage());
        }finally {
            ctx.close();
        }
    }

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

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

public class SimpleChatServerInitializer  extends ChannelInitializer<SocketChannel>{

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        // 自定义处理类
        ch.pipeline().addLast(new NettyServerHandler());
    }

}

这边我客户端是用stocket 现实的,方便把。 有兴趣的可以把netty 的客户端的实现方式列出来。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Netty 是一个基于 NIO(Non-blocking I/O)的框架,用于快速开发可伸缩的网络应用程序。在 Netty 中,服务端接受和发送消息是通过 ChannelHandler 来实现的。 对于服务端接受消息,首先需要创建一个 ServerBootstrap 实例,并设置一系列的参数。然后通过调用 bind() 方法绑定监听端口,在新连接到来时,会创建一个新的 Channel(通道)来处理客户端的请求。此时,我们可以注册一个 ChannelHandler,继承自 SimpleChannelInboundHandler,来处理客户端发送的消息。在重写的 channelRead0() 方法中,我们可以获取客户端发送的消息,并进行相应的处理,例如解码、验证等。然后,我们可以利用 ChannelHandlerContext 对象的 writeAndFlush() 方法将响应消息返回客户端。 对于服务端发送消息,可以在接受客户端请求的过程中,在处理完请求后直接进行发送,也可以通过一些其他的触发事件来发送消息。无论是哪种方式,我们都需要通过 ChannelHandlerContext 对象的 writeAndFlush() 方法将消息写入通道,并发送给客户端。在编写消息时,我们可以根据协议规范进行相应的编码操作,将高层次的数据类型转化为字节流,再进行发送。 通过使用 Netty,我们可以轻松地实现服务端接受和发送消息的功能。其中,服务端接受消息需要注册相应的 ChannelHandler,重写其 channelRead0() 方法来处理客户端发送的消息;服务端发送消息则需要使用 ChannelHandlerContext 对象的 writeAndFlush() 方法来将消息写入通道。同时,Netty 的高性能和可伸缩性能够满足大规模并发请求的需求,使得开发网络应用程序变得更加简单和高效。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值