netty学习(3):SpringBoot整合netty实现多个客户端与服务器通信

news2024/9/21 16:42:17

1. 创建SpringBoot父工程

创建一个SpringBoot工程,然后创建三个子模块
整体工程目录:一个server服务(netty服务器),两个client服务(netty客户端)
在这里插入图片描述
pom文件引入netty依赖,springboot依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>pom</packaging>
    <modules>
        <module>server</module>
        <module>client1</module>
        <module>client2</module>
    </modules>

    <!--继承 SpringBoot 框架的一个父项目,所有自己开发的 Spring Boot 都必须的继承-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>org.example</groupId>
    <artifactId>nettyTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!--SpringBoot 框架 web 项目起步依赖,通过该依赖自动关联其它依赖,不需要我们一个一个去添加-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.34.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.23</version>
        </dependency>
    </dependencies>
</project>

2. 创建Netty服务器

在这里插入图片描述
NettySpringBootApplication

package server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class NettySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(NettySpringBootApplication.class, args);
    }
}

NettyServiceHandler

package server.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class NettyServiceHandler extends SimpleChannelInboundHandler<String> {
    private static final ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 获取到当前与服务器连接成功的channel
        Channel channel = ctx.channel();
        group.add(channel);
        System.out.println(channel.remoteAddress() + " 上线," + "在线数量:" + group.size());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 获取到当前要断开连接的Channel
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + "下线," + "在线数量:" + group.size());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("netty客户端" + channel.remoteAddress() + "发送过来的消息:" + msg);
        group.forEach(ch -> { // JDK8 提供的lambda表达式
            if (ch != channel) {
                ch.writeAndFlush(channel.remoteAddress() + ":" + msg + "\n");
            }
        });
    }

    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
        throwable.printStackTrace();
        channelHandlerContext.close();
    }
}

SocketInitializer

package server.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Component;

@Component
public class SocketInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
//        // 添加对byte数组的编解码,netty提供了很多编解码器,你们可以根据需要选择
//        pipeline.addLast(new ByteArrayDecoder());
//        pipeline.addLast(new ByteArrayEncoder());

        //添加一个基于行的解码器
        pipeline.addLast(new LineBasedFrameDecoder(2048));
        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new StringEncoder());

        // 添加上自己的处理器
        pipeline.addLast(new NettyServiceHandler());
    }
}

NettyServer

package server.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class NettyServer {
    private final static Logger logger = LoggerFactory.getLogger(NettyServer.class);

    @Resource
    private SocketInitializer socketInitializer;

    @Getter
    private ServerBootstrap serverBootstrap;

    /**
     * netty服务监听端口
     */
    @Value("${netty.port:6666}")
    private int port;
    /**
     * 主线程组数量
     */
    @Value("${netty.bossThread:1}")
    private int bossThread;

    /**
     * 启动netty服务器
     */
    public void start() {
        this.init();
        this.serverBootstrap.bind(this.port);
        logger.info("Netty started on port: {} (TCP) with boss thread {}", this.port, this.bossThread);
    }

    /**
     * 初始化netty配置
     */
    private void init() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.bossThread);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        this.serverBootstrap = new ServerBootstrap();
        this.serverBootstrap.group(bossGroup, workerGroup) // 两个线程组加入进来
                .channel(NioServerSocketChannel.class)  // 配置为nio类型
                .option(ChannelOption.SO_BACKLOG, 128) //设置线程队列等待连接个数
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(this.socketInitializer); // 加入自己的初始化器
    }
}

NettyStartListener

package server.netty;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 监听Spring容器启动完成,完成后启动Netty服务器
 * @author Gjing
 **/
@Component
public class NettyStartListener implements ApplicationRunner {
    @Resource
    private NettyServer nettyServer;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.nettyServer.start();
    }
}

application.yml

server:
  port: 8000

netty:
  port: 6666
  bossThread: 1

3. 创建Netty客户端

在这里插入图片描述
Client1

package client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Client1 {
    public static void main(String[] args) {
        SpringApplication.run(Client1.class, args);
    }
}

NettyClientHandler

package client.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyClientHandler extends SimpleChannelInboundHandler<String> {
    public void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) {
        System.out.println("收到服务端消息:" + channelHandlerContext.channel().remoteAddress() + "的消息:" + msg);
    }

    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
        channelHandlerContext.close();
    }
}

SocketInitializer

package client.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Component;

@Component
public class SocketInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new LineBasedFrameDecoder(2048));
        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new StringEncoder());
        pipeline.addLast(new NettyClientHandler()); //加入自己的处理器
    }
}

NettyClient

package client.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class NettyClient {
    private final static Logger logger = LoggerFactory.getLogger(NettyClient.class);

    @Resource
    private SocketInitializer socketInitializer;

    @Getter
    private Bootstrap bootstrap;

    @Getter
    private Channel channel;
    /**
     * netty服务监听端口
     */
    @Value("${netty.port:6666}")
    private int port;

    @Value("${netty.host:127.0.0.1}")
    private String host;

    /**
     * 启动netty
     */
    public void start() {
        this.init();
        this.channel = this.bootstrap.connect(host, port).channel();
        logger.info("Netty connect on port: {}, the host {}, the channel {}", this.port, this.host, this.channel);
        try {
            InputStreamReader is = new InputStreamReader(System.in, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(is);
            while (true) {
                System.out.println("输入:");
                this.channel.writeAndFlush(br.readLine() + "\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化netty配置
     */
    private void init() {
        EventLoopGroup group = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        //设置线程组
        bootstrap.group(group)
                .channel(NioSocketChannel.class) //设置客户端的通道实现类型
                .handler(this.socketInitializer);
    }
}

NettyStartListener

package client.netty;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class NettyStartListener implements ApplicationRunner {
    @Resource
    private NettyClient nettyClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.nettyClient.start();
    }
}

application.yml

server:
  port: 8001

netty:
  port: 6666
  host: "127.0.0.1"

然后按照相同的方法创建client2

4. 测试

在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/714282.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

国企一面会问什么?

前言&#xff1a; \textcolor{Green}{前言&#xff1a;} 前言&#xff1a; &#x1f49e;快秋招了&#xff0c;那么这个专栏就专门来记录一下&#xff0c;同时呢整理一下常见面试题 &#x1f49e;部分题目来自自己的面试题&#xff0c;部分题目来自网络整理 国企注重的和私企会…

中国各地区新能源汽车产量(2015-2022年) 共13个指标

从各地区统计公报、各地区统计年鉴整理了69个省市的新能源汽车产量数据&#xff0c;并提供了包含原始数据的各个来源。数据显示&#xff0c;中国各地区的新能源汽车产量存在着明显的区域差异。该数据可为各研究人员提供重要参考&#xff0c;有助于制定地方产业发展规划和市场战…

ruoyi-vue | electron打包教程(超详细)

公司项目由于来不及单独做客户端了&#xff0c;所以想到用electron直接将前端打包程exe,dmg等格式的安装包。 由于使用的ruoyi-vue框架开发&#xff0c;所以这篇教程以ruoyi-vue为基础的。 环境说明 nodejs&#xff1a;v16.18.1npm&#xff1a;8.19.2ruoyi-vue&#xff1a;3.8…

基于SQLI的SQL字符型报错注入

基于SQLI的SQL字符型报错注入 一. 实验目的 理解数字型报错SQL注入漏洞点的定位方法&#xff0c;掌握利用手工方式完成一次完整SQL注入的过程&#xff0c;熟悉常见SQL注入命令的操作。 二. 实验环境 渗透主机&#xff1a;KALI平台 用户名: college 密码: 360College 目标网…

Windows 10 执行wsl命令报错: --list -o命令行选项无效 --update命令行选项无效等解决办法

问题说明 在使用wsl命令的时候&#xff0c;wsl --update&#xff0c;wsl --list -o等关键的命令都显示命令行选项无效 但是wsl这个命令却又是一个有效的命令 解决办法 1.卸载旧版本的WSL 没有子系统可以跳过这个步骤 打开命令提示符或PowerShell窗口&#xff08;以管理员身…

深蓝学院C++基础与深度解析笔记 第 10 章 泛型算法与 Lambda 表达式

第 10 章 泛型算法与 Lambda 表达式 1. 泛型算法 1.1 泛型算法&#xff1a; 可以支持多种类型的算法。 int x[100]; std::sort(std: : begin(x), std : :end(x));1.11 这里重点讨论 C 标准库中定义的算法&#xff1a; <algorithm > <numeric> <ranges> 1.…

简洁清新后台模板推荐(光年)

目录 前言一、后台模板介绍1.作者介绍2.模板介绍 二、界面展示1.登录2.首页3.UI元素4.表单5.工具类6.示例页面7.主题选择 三、入口总结 前言 作为后端开发人员&#xff0c;前端技术确实不精通&#xff0c;也没有太多的精力搞前端。所以一直在搜寻一些现成的模板。最近发现一个…

基于单片机的盲人导航智能拐杖老人防丢防摔倒发短息定位

功能介绍 以STM32单片机作为主控系统&#xff1b; OLED液晶当前实时距离&#xff0c;安全距离&#xff0c;当前经纬度信息&#xff1b;超声波检测小于设置的安全距离&#xff0c;蜂鸣器报警提示&#xff1a;低于安全距离&#xff01;超声波检测当前障碍物距离&#xff0c;GPS进…

Linux-CentOS7版本的系统搭建达梦数据库

目录 VMware中安装CentOS 7.5并做相关的配置搭建Docker环境搭建达梦数据库拉取镜像查看镜像命令为镜像设置一个别名根据镜像 创建一个容器 根据镜像 创建一个容器启动并进入容器 VMware中安装CentOS 7.5并做相关的配置 使用VMware安装CentOS7的虚拟机可以参考另外一篇文章&…

netwox构造免费ARP数据包【网络工程】(保姆级图文)

目录 构造免费的 ARP 数据包。1) 构造免费的 ARP 数据包2) 使用 Wireshark 进行抓包 总结 欢迎关注 『网络工程专业』 系列&#xff0c;持续更新中 欢迎关注 『网络工程专业』 系列&#xff0c;持续更新中 温馨提示&#xff1a;对虚拟机做任何设置&#xff0c;建议都要先快照备…

Android修改符盘名称与蓝牙名称

修改符盘名称 android\frameworks\base\media\java\android\mtp\MtpDatabase.java 修改蓝牙名称 android\system\bt\btif\src\btif_dm.cc 注&#xff1a;尽量不在build与device文件下修改设备名称&#xff0c;因为这是套指纹的软件 这里的值必须和之前的软件是一样的

Spring Cloud Feign: 了解、原理和使用

Spring Cloud Feign: 了解、原理和使用 Spring Cloud Feign 是 Spring Cloud 生态系统中的一个重要组件&#xff0c;它提供了一种声明式的、基于注解的 REST 客户端&#xff0c;能够方便地实现服务之间的调用和通信。在本文中&#xff0c;我们将介绍 Spring Cloud Feign 的概念…

链码的打包与升级

目录 1、链码的打包与签名 ​编辑 对链码的签名 1、安装已经添加签名的链码 2、安装成功之后进行链码的实例化操作&#xff0c;同时指定其背书策略 测试 1、查询链码 2、调用链码 3、查询链码 链码的升级 1、安装链码 2、升级链码 3、测试 1、查询 2、调用 3、…

【花雕】全国青少年机器人技术一级考试备考实操搭建手册3

目录 1、秋千 2、跷跷板 3、搅拌器 4、奇怪的钟 5、起重机 6、烤肉架 7、手摇风扇 8、履带车 9、直升机 10、后轮驱动车 搅拌器是一种可以帮助我们将不同的物质混合在一起的机器。它通常由一个电动机和一个搅拌器头组成。当我们把需要混合的物质放入容器中&#xff0c;打开搅拌…

C语言之函数递归

前言   从前有座山&#xff0c;山里有座庙&#xff0c;庙里有个老和尚&#xff0c;正在给小和尚讲故事呢&#xff01;故事是什么呢&#xff1f;"从前有座山&#xff0c;山里有座庙&#xff0c;庙里有个老和尚&#xff0c;正在给小和尚讲故事呢&#xff01;故事是什么呢&…

字典树的数据结构

Trie字典树主要用于存储字符串&#xff0c;Trie 的每个 Node 保存一个字符。用链表来描述的话&#xff0c;就是一个字符串就是一个链表。每个Node都保存了它的所有子节点。 例如我们往字典树中插入see、pain、paint三个单词&#xff0c;Trie字典树如下所示&#xff1a; 也就是…

zookeeper的动态扩容

附属意义的扩容&#xff1a;扩容的新增节点为观察者observer 1.观察者概念&#xff1a; a.在zookeeper引入此新的zookeeper节点类型为observer&#xff0c;是为了帮助处理投票成本随着追随者增加而增加的问题并且进一步完善了zookeeper的可扩展性 b.观察者不参与投票&#x…

【机器学习】基于卷积神经网络 CNN 的猫狗分类问题

文章目录 一、卷积神经网络的介绍1.1 什么是卷积神经网络1.2 重要层的说明1.3 应用领域二、 软件、环境配置2.1 安装Anaconda2.2 环境准备 三、猫狗分类示例3.1 图像数据预处理3.2 基准模型3.3 数据增强3.4 dropout层四、总结 一、卷积神经网络的介绍 1.1 什么是卷积神经网络 …

决策树ID3

文章目录 题目一基础知识解题过程①算总的信息量②求解各个指标的信息增益&#xff0c;以此比较得出根节点③ 从根节点下的晴天节点出发循环上述步骤④ 从根节点下的多云节点出发&#xff0c;循环上述步骤⑤ 从根节点下的雨节点出发&#xff0c;循环上述步骤⑥画出最终的决策树…

ChatGPT实战:职业生涯规划

ChatGPT的出现&#xff0c;不仅改变了人们对人工智能技术的认识&#xff0c;也对经济社会发展产生了深远的影响。那么&#xff0c;在ChatGPT时代&#xff0c;人们应该如何规划自己的职业呢&#xff1f; 职业规划是一个有意义且重要的过程&#xff0c;它可以帮助你在职业生涯中取…