基于Java-SpringBoot框架的netty简单使用

工作需要大致进行了学习,并不深入,只是简单的使用,若存在错误,欢迎大家指正,在后续系统学习后会更加深入的解释其中的配置。

一、netty模块配置 

 1.netty的依赖注入

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
</dependency>

2、netty服务端配置

nettyServer配置

    //创建成员变量主线程与工作线程
    //一个主线程
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    //工作线程
    NioEventLoopGroup workGroup = new NioEventLoopGroup(200);

    //初始化服务配置(主要是对ServerBootstrap的配置),通过bind方法绑定监听ip端口的消息
    InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8082);
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workGroup)
                //指定channel
                .channel(NioServerSocketChannel.class)
                //使用指定的端口设置套接字地址
                .localAddress(inetSocketAddress)
                //指定日志级别
                .handler(new LoggingHandler(LogLevel.INFO))
                //设置服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
                .option(ChannelOption.SO_BACKLOG, 1024)
                //两小时没有数据通信时TCP会自动发送一个活动探测数据报文
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                //添加自定义的初始化器
                .childHandler(new ServerInitializer());
        try {
            ChannelFuture future = serverBootstrap.bind(inetSocketAddress).sync();
            log.info("tcp服务开始监听端口:{}", inetSocketAddress.getPort());
            if (future.isSuccess()) {
                log.info("netty启动成功");
            }
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

ServerInitializer配置

在nettyServer中serverBootstrap的配置中配置了.childHandler(new ServerInitializer()),该类需要继承ChannelInitializer<SocketChannel>,
并实现initChannel(SocketChannel socketChannel)方法,主要是用于指定编码器与解码器;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //String类的解码器
        pipeline.addLast(new StringDecoder());
        //String类的编码器
        pipeline.addLast(new StringEncoder());
        //配置server的处理器(对于消息的接收与处理等行为)
        pipeline.addLast(new NettyServerHandler());
    }

NettyServerHandler配置

在ServerInitializer中配置了 pipeline.addLast(new NettyServerHandler()),NettyServerHandler处理器需要继承SimpleChannelInboundHandler<XXXX>其中XXX为接收消息的对象类型,
并实现channelRead0(ChannelHandlerContext channelHandlerContext, XXXX xxx)方法(其中XXX为继承时的泛型类型),此处为打印netty接收到的消息。

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String str) throws Exception {
        System.out.println(str);
    }

3、netty客户端配置

nettyClient配置

客户端与服务端相似,不同的是服务端配置的ServerBootstrap客户端配置的是Bootstrap,bootstrap的connect方法指定连接到的ip与端口,消息会发往连接到的ip端口(使用bootstrap.connect()方法返回的对象的writeAndFlush方法写入对象发送)。

    //配置线程组
    NioEventLoopGroup group = new NioEventLoopGroup();

    public void run(Object msg) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                //指定channel
                .channel(NioSocketChannel.class)
                .handler(new ServerInitializer());
        //连接
        ChannelFuture connect;
        try {
            connect = bootstrap.connect("127.0.0.1", 8082).sync();
            Channel channel = connect.channel();
            log.info("连接netty成功");
            channel.writeAndFlush(msg);
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

ClientInitializer配置

与serverInitializer相似,继承ChannelInitializer<SocketChannel>后实现initChannel(SocketChannel socketChannel)指定编码、解码器,并指定handler处理器。

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //String类的解码器
        pipeline.addLast(new StringDecoder());
        //String类的编码器
        pipeline.addLast(new StringEncoder());
        pipeline.addLast(new NettyClientHandler());
    }

NettyClientHandler配置

客户端的NettyClientHandler继承SimpleChannelInboundHandler<PersonOuterClass.Person>
实现channelRead0(ChannelHandlerContext channelHandlerContext, PersonOuterClass.Person person),根据业务需要实现该方法。其中的XXX为接收的参数类型。channelActive(ChannelHandlerContext ctx)在连接成功时会被触发。

​
@Slf4j
public class NettyClientHandler extends SimpleChannelInboundHandler<XXX> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, XXX xxx) throws Exception {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接成功");
    }
}

​

System.out.println("感谢阅读");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring BootNetty SocketIO相结合可以实现实时通信的功能。下面是一个简单的步骤来整合这两个框架: 1. 添加Maven依赖 在pom.xml文件添加以下依赖: ```xml <dependency> <groupId>com.corundumstudio.socketio</groupId> <artifactId>netty-socketio</artifactId> <version>1.7.16</version> </dependency> ``` 2. 创建一个SocketIO服务器 在Spring Boot应用程序,可以通过创建一个Bean来创建一个SocketIO服务器。 ```java @Configuration public class SocketIOConfig { @Bean public SocketIOServer socketIOServer() { Configuration config = new Configuration(); config.setHostname("localhost"); config.setPort(9092); SocketIOServer server = new SocketIOServer(config); return server; } } ``` 3. 创建一个SocketIO事件处理器 为了处理收到的SocketIO事件,需要创建一个SocketIO事件处理器。可以通过实现`SocketIOListener`接口来创建它。 ```java @Component public class ChatEventListener implements SocketIONamespaceListener { private SocketIOServer server; @Autowired public ChatEventListener(SocketIOServer server) { this.server = server; } @Override public void onConnect(SocketIOClient client) { System.out.println("Client connected: " + client.getSessionId()); } @Override public void onDisconnect(SocketIOClient client) { System.out.println("Client disconnected: " + client.getSessionId()); } @Override public void onConnect(SocketIOClient client, String namespace) { System.out.println("Client connected to namespace: " + client.getSessionId() + " - " + namespace); } @Override public void onDisconnect(SocketIOClient client, String namespace) { System.out.println("Client disconnected from namespace: " + client.getSessionId() + " - " + namespace); } } ``` 4. 注册SocketIO事件处理器 将事件处理器注册到SocketIO服务器。 ```java @Configuration public class SocketIOConfig { @Bean public SocketIOServer socketIOServer() { Configuration config = new Configuration(); config.setHostname("localhost"); config.setPort(9092); SocketIOServer server = new SocketIOServer(config); server.addNamespace("/chat").addListeners(new ChatEventListener(server)); return server; } } ``` 5. 启动SocketIO服务器 在Spring Boot应用程序的启动类,可以通过启动SocketIO服务器来启动整个应用程序。 ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); SocketIOServer server = ctx.getBean(SocketIOServer.class); server.start(); } } ``` 现在整合完成了,可以使用SocketIO客户端连接到服务器并发送事件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值