springboot+Netty+websocket请求聊天室接口开发

前提概要

会maven聚合工程构建springboot项目,会使用postman即可

整理了用户上线功能,一对一聊天功能,前端用postman发起websocket请求来才测试,(不用写什么狗屎前端页面)测试完成后,通过http请求到后端Controller发送消息,一步一步手把手带你写,简单到爆炸,隔壁50岁的测试老妈子都学会了。

请添加图片描述

maven聚合工程构建

在这里插入图片描述

父工程pom.xml

<?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>

    <groupId>org.springboot.module</groupId>
    <artifactId>springboot-module-master</artifactId>
    <packaging>pom</packaging>
    <version>1.0</version>
    <modules>
        <module>springboot-all</module>
        <module>springboot-common</module>
        <module>springboot-netty</module>
    </modules>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <springbootModule.version>1.0</springbootModule.version>
        <lombok.version>1.16.20</lombok.version>
        <fastjson.version>1.2.83</fastjson.version>
        <hutool.version>5.8.18</hutool.version>
        <netty.version>4.1.68.Final</netty.version>
    </properties>
    <!-- 依赖声明
            dependencyManagement只是声明依赖,并不实现引入,因此子项目需要显示的声明需要用的依赖。
            如果不在子项目中声明依赖,是不会从父项目中继承下来;
            只有在子项目中写了该依赖项,并且没有指定具体版本,才会从父项目中继承该项,
            并且version和scope都读取自父pom;另外如果子项目中指定了版本号,那么会使用子项目中指定的jar版本。
            -->
    <dependencyManagement>
        <dependencies>
            <!-- SpringBoot的依赖配置-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.7.11</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--lombok依赖-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>
            <!--fastJson依赖-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>${fastjson.version}</version>
            </dependency>
            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>${hutool.version}</version>
            </dependency>
            <!--netty依赖包-->
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-all</artifactId>
                <version>${netty.version}</version>
            </dependency>
            <!--公共工具模块-->
            <dependency>
                <groupId>org.springboot.module</groupId>
                <artifactId>springboot-common</artifactId>
                <version>${springbootModule.version}</version>
            </dependency>
            <!--netty案例模块-->
            <dependency>
                <groupId>org.springboot.module</groupId>
                <artifactId>springboot-netty</artifactId>
                <version>${springbootModule.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

公共工具模块pom.xml

<?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">
    <parent>
        <artifactId>springboot-module-master</artifactId>
        <groupId>org.springboot.module</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>springboot-common</artifactId>
    <description>公共工具模块</description>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 表示依赖不会传递 -->
        </dependency>
        <!-- Spring框架基本的核心工具 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
        </dependency>
    </dependencies>

</project>

netty案例模块

<?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">
    <parent>
        <artifactId>springboot-module-master</artifactId>
        <groupId>org.springboot.module</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>springboot-netty</artifactId>
    <description>netty案例模块</description>
    <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
        </dependency>
        <!--引入公共工具模块-->
        <dependency>
            <groupId>org.springboot.module</groupId>
            <artifactId>springboot-common</artifactId>
        </dependency>
    </dependencies>
</project>

启动类模块

<?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">
    <parent>
        <artifactId>springboot-module-master</artifactId>
        <groupId>org.springboot.module</groupId>
        <version>1.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>springboot-all</artifactId>
    <description>web服务入口</description>
    <dependencies>

        <!--引入netty案例模块-->
        <dependency>
            <groupId>org.springboot.module</groupId>
            <artifactId>springboot-netty</artifactId>
        </dependency>
    </dependencies>

</project>

创建springboot启动类

写完启动测试是否成功

创建UserController

在这里插入图片描述

启动springboot测试是否可以访问成功

在这里插入图片描述

创建实体类、枚举

在这里插入图片描述

创建nettyConfig配置类

在这里插入图片描述

package com.demo.netty.config;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Netty配置类
 * @author:AKS
 */
@Configuration
public class NettyConfig {

    /**
     * 存储所有在线的客户端Channel
     *
     *ChannelGroup是Netty中的一种特殊的Channel容器,用于管理多个Channel对象。
     * 它可以用来跟踪和管理与服务器建立的所有活动连接。
     *      广播消息:可以通过ChannelGroup向其中的所有Channel广播消息,实现一次性向多个客户端发送相同的消息。
     *      批量操作:可以对ChannelGroup中的所有Channel进行批量操作,例如批量关闭连接、批量发送消息等。
     *      管理连接:通过ChannelGroup可以方便地管理和跟踪与服务器建立的连接,包括添加新的连接、删除断开的连接、获取连接数量等。
     * 使用ChannelGroup可以有效地管理多个Channel,简化了对连接的管理和操作,特别适用于需要同时处理多个连接的情况,例如实现聊天室、推送系统等。
     */
    private static final ChannelGroup onlineChannelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 存储所有在线的UserId与之对应的Channel
     *
     * ConcurrentHashMap是Java中的一个线程安全的哈希表实现类,它继承自AbstractMap类,实现了ConcurrentMap接口。
     * 与HashMap相比,ConcurrentHashMap在多线程环境下提供了更好的并发性能和线程安全性。
     * 它采用了分段锁的机制,将整个哈希表分成多个段(Segment),每个段维护一个独立的哈希表。
     * 不同的线程可以同时访问不同的段,从而实现了并发读写的能力。
     */
    private static final ConcurrentMap<String, Channel> onlineUserChannelMap = new ConcurrentHashMap<>();

    /**
     * 获取所有在线的客户端Channel
     */
    public static ChannelGroup getOnlineChannelGroup() {
        return onlineChannelGroup;
    }

    /**
     * 获取所有在线的UserId与之对应的Channel
     */
    public static ConcurrentMap<String, Channel> getOnlineUserChannelMap() {
        return onlineUserChannelMap;
    }
}

创建NettyServetTextHandler、NettyServerInitializer

在这里插入图片描述

package com.demo.netty.handler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
 * 自定义Handler需要继承netty规定好的某个HandlerAdapter(规范)
 *@ChannelHandler.Sharable  注解的作用
 *  是使一个ChannelHandler实例可被多个ChannelPipeline共享使用,提高性能和资源利用,并需要确保线程安全性。
 *  WebSocketFrame 是Netty中提供的一个类,它是对WebSocket协议中的帧(Frame)进行了封装。
 *  帧是WebSocket通信的基本单位,它可以包含各种类型的数据,并且帧之间可以按照一定的协议顺序进行传输。
 * @author:AKS
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyServerTextHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    /**
     * 当客户端连接服务器完成就会触发该方法
     * 当 Channel 的连接建立并准备好接收数据时被调用。这意味着连接已经成功建立,可以开始发送和接收数据了。
     *在每次连接激活时被调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端连接建立通道完成...可以开始发送数据..");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame webSocketFrame) throws Exception {
        /**
         *  把 WebSocketFrame 强转成 TextWebSocketFrame 处理文本消息
         */
        TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) webSocketFrame;
        log.info("客户端===============: " + textWebSocketFrame.text());

    }

}

package com.demo.netty.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author:AKS
 */
@Slf4j
@AllArgsConstructor
public class NettyServerInitializer extends ChannelInitializer<NioSocketChannel> {

    /**
     * WebSocket 服务的接口地址
     */
    public String path;
    /**
     *  Netty 消息帧最大体积
     */
    private long maxFrameSize;


    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        log.info("服务的接口地址:{}", path);
        ChannelPipeline pipeline = ch.pipeline();
        //HTTP协议编解码器,用于处理HTTP请求和响应的编码和解码。其主要作用是将HTTP请求和响应消息转换为Netty的ByteBuf对象,并将其传递到下一个处理器进行处理。
        pipeline.addLast(new HttpServerCodec());
        //用于HTTP服务端,将来自客户端的HTTP请求和响应消息聚合成一个完整的消息,以便后续的处理。
        pipeline.addLast(new HttpObjectAggregator(65536));
        //用于对WebSocket消息进行压缩和解压缩操作。
        pipeline.addLast(new WebSocketServerCompressionHandler());
        // 支持分块写入  在网络通信中,如果要传输的数据量较大,直接将数据一次性写入到网络缓冲区可能会导致内存占用过大或者网络拥塞等问题
        pipeline.addLast(new ChunkedWriteHandler());
        //这行很重要
        pipeline.addLast(new WebSocketServerProtocolHandler(path, null, true, maxFrameSize));
        pipeline.addLast(new NettyServerTextHandler());
    }
}

创建 NettyServer

在这里插入图片描述

package com.demo.netty.server;

import com.demo.netty.handler.NettyServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author:AKS
 * @Component:定义Spring管理Bean(也就是将标注@Component注解的类交由spring管理)
 */
@Slf4j
@Component
public class NettyServer {
    /**
     * Netty 服务端口号
     */
    @Value("${netty.websocket.port}")
    private int port;
    /**
     * Netty 服务path
     */
    @Value("${netty.websocket.path}")
    private String path;
    /**
     *  Netty 消息帧最大体积
     */
    @Value("${netty.websocket.max-frame-size}")
    private long maxFrameSize;
    /**
     *  主线程组 只处理连接请求
     */
    private EventLoopGroup bossGroup;
    /**
     *  子线程组 处理业务
     */
    private EventLoopGroup workerGroup;
    /**
     *  服务器端的启动对象(ServerBootstrap是服务端启动引导类)
     */
    private ServerBootstrap serverBootstrap;

    /**
     * 启动netty服务器
     */
    private void start(){
        /**
         * 实例化 主、子 线程组,服务端启动引导类
         */
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyServerInitializer(path,maxFrameSize));
        try {
            ChannelFuture future = serverBootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }

    /**
     * 初始化WebSocketServer(调用init())
     * PostConstruct注解:用于指示一个方法在容器创建该组件之后立即调用
     *  注解使用前提:该类的实例必须是由容器创建和管理的,如 Spring、JavaEE 容器等。
     */
    @PostConstruct
    public void init(){
        //这里要新开一个线程,否则会阻塞原本的controller等业务
        new Thread(() -> {
            start();
        }).start();
    }
}

启动项目PostMan发起webSocket测试

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
看到以下结果表示成功连接服务,并可以发送消息了
在这里插入图片描述

上线下线功能

重构 NettyServetTextHandler

package com.demo.netty.handler;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.demo.netty.config.NettyConfig;
import com.demo.netty.enums.MessageTypeEnum;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 自定义Handler需要继承netty规定好的某个HandlerAdapter(规范)
 *
 * @ChannelHandler.Sharable 注解的作用
 * 是使一个ChannelHandler实例可被多个ChannelPipeline共享使用,提高性能和资源利用,并需要确保线程安全性。
 * WebSocketFrame 是Netty中提供的一个类,它是对WebSocket协议中的帧(Frame)进行了封装。
 * 帧是WebSocket通信的基本单位,它可以包含各种类型的数据,并且帧之间可以按照一定的协议顺序进行传输。
 * @author:AKS
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyServerTextHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    /**
     * 存储在 Channel 中的 attr 属性名(存储用户Id)
     */
    public static final String USER_ID = "userId";

    /**
     * 当客户端连接服务器完成就会触发该方法
     * 当 Channel 的连接建立并准备好接收数据时被调用。这意味着连接已经成功建立,可以开始发送和接收数据了。
     * 在每次连接激活时被调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端连接建立通道完成...可以开始发送数据..");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame webSocketFrame) throws Exception {
        /**
         *  把 WebSocketFrame 强转成 TextWebSocketFrame 处理文本消息
         */
        TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) webSocketFrame;
        log.info("客户端===============: " + textWebSocketFrame.text());
        /**
         * 前端测试是以json格式字符串发送过来的
         * 例如:"{'type':'ONLINE','userId':'Andy'}"
         * 所以在这里对其转换成json并根据key取出对应的value
         */
        // 解析JSON字符串
        String jsonStr = textWebSocketFrame.text();
        JSONObject jsonObj = JSONUtil.parseObj(jsonStr);
        String type = jsonObj.getStr("type");
        MessageTypeEnum messageTypeEnum = MessageTypeEnum.valueOf(type);
        if (MessageTypeEnum.ONLINE.compareTo(messageTypeEnum) == 0) {
            //获取上线用户id
            String userId = jsonObj.getStr("userId");
            //用户上线
            userOnline(channelHandlerContext, userId);
        } else if (MessageTypeEnum.TEXT.compareTo(messageTypeEnum) == 0) {
            //发送普通文本消息
            sendMessage(jsonStr, channelHandlerContext.channel());
        }
    }

    /**
     * 用户上线
     */
    private void userOnline(ChannelHandlerContext channelHandlerContext, String userId) {
        //注册客户端
        //给 Channel 绑定一个存储 UserId 的 AttributeKey
        Channel channel = channelHandlerContext.channel();
        //设置一个名为 userId 的 AttributeKey
        AttributeKey<Object> userIdKey = AttributeKey.valueOf("userId");
        //将 Channel 的 attr 设置一个名为 userId
        channel
                //在 Channel 中寻找名为 userIdKey 的 AttributeKey
                .attr(userIdKey)
                //给这个 AttributeKey 设置值
                .set(userId);
        //调用自定义的NettyConfig工具类的getOnlineUserChannelMap方法,将UserId与Channel建立联系
        NettyConfig.getOnlineUserChannelMap().put(userId, channel);
        log.info("在线用户 --> {}", NettyConfig.getOnlineUserChannelMap().keySet());
        //调用自定义的NettyConfig工具类的getOnlineChannelGroup方法:通知所有用户,userId上线了
        NettyConfig.getOnlineChannelGroup().writeAndFlush(new TextWebSocketFrame(
                "用户:【" + userId + "】上线啦!"
        ));
    }

    /**
     * 发送普通文本消息
     */
    private void sendMessage(String jsonStr, Channel channel) {

    }

    /**
     * 在新的 Channel 被添加到 ChannelPipeline 中时被调用。
     * 这通常发生在连接建立时,即 Channel 已经被成功绑定并注册到 EventLoop 中。
     * 在连接建立时被调用一次,不建立连接不调用
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将新连接的客户端Channel存储起来
        NettyConfig.getOnlineChannelGroup().add(channel);
        log.info("新客户端建立链接 --> {},在线用户数量:{}", channel.id(), NettyConfig.getOnlineChannelGroup().size());
    }

    /**
     * 删除断开连接的客户端在程序中的数据
     */
    private void cleanChannel(Channel channel) {
        //获取客户端 Channel 中存储的名为 userId 的 Attribute
        Attribute<String> userIdKey = channel.attr(AttributeKey.valueOf(USER_ID));
        String userId = userIdKey.get();
        //从 ChannelGroup 中移除断开的 Channel
        NettyConfig.getOnlineChannelGroup().remove(channel);
        //从 Map 中移除 UserId 与 Channel 的对照关系
        NettyConfig.getOnlineUserChannelMap().remove(userId);

        //通知所有用户某用户下线了
        NettyConfig.getOnlineChannelGroup().writeAndFlush(new TextWebSocketFrame(
                "用户:【" + userId + "】下线啦!"
        ));
    }

    /**
     * 在 WebSocket 连接断开时,Netty 会自动触发 channelInactive 事件,并将该事件交给事件处理器进行处理。
     * 在 channelInactive 事件的处理过程中,会调用 handlerRemoved 方法,用于进行一些资源释放等操作,确保 WebSocket 连接正常断开。
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //移除断开的客户端的Channel
        Channel channel = ctx.channel();
        cleanChannel(channel);
        log.info("客户端断开链接 --> {},在线用户数量:{}", channel.id(), NettyConfig.getOnlineChannelGroup().size());
    }

    /**
     * 当客户端断开服务器就会触发该方法
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        System.out.println("客户端连接断开完成.....");
    }

    /**
     * 处理异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //获取断开连接的客户端的Channel
        Channel channel = ctx.channel();
        //移除断开的客户端的Channel
        cleanChannel(channel);
        log.info("客户端异常断开 --> {},在线用户数量:{}", channel.id(), NettyConfig.getOnlineChannelGroup().size());
        //当发生异常时,手动关闭Channel
        channel.close();
    }

}

测试

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

在这里插入图片描述
点击PostMan的Disconnect断开连接,在Andy端查看
在这里插入图片描述
在这里插入图片描述

一对一发送消息

重构 NettyServetTextHandler

 	/**
     * 发送普通文本消息
     */
    private void sendMessage(String jsonStr, Channel channel) {
        //把前端传过来的json字符串转换成Message实体对象
        Message message = JSONUtil.toBean(jsonStr,Message.class);
        // 获取用户id
        String userId = message.getUserId();
        //获取用户发送消息内容
        String userMsg = message.getMsg();
        //获取接受者id
        String receiver = message.getReceiver();
        //通过自定义的NettyConfig工具类的getOnlineUserChannelMap方法,获取之前上线方法里面存的指定用户的管道
        Channel receiverChannel = NettyConfig.getOnlineUserChannelMap().get(receiver);
        if(Objects.nonNull(receiverChannel)){
            //TODO 这里可以设计为结构化的数据,以返回JSON数据便于解析
            receiverChannel.writeAndFlush(new TextWebSocketFrame(userId + ":" + userMsg));
        }
        log.info("用户【{}】给【{}】发送的消息:{}", userId, receiver, userMsg);
        //TODO 服务端给客户端回复消息(可以设计为失败时返回)
        channel.writeAndFlush(new TextWebSocketFrame("服务端已接收到消息"));
    }

测试:上线3个用户 Andy、Mike、Bluce

在这里插入图片描述
接收人是MIke,所以只有Mike才能看的到消息,其他用户看不到消息
在这里插入图片描述
在这里插入图片描述

通过http请求给用户发送消息

业务层及其接口

在这里插入图片描述

SendMessageService

package com.demo.netty.service;

import com.demo.netty.entity.Message;

/**
 * 该接口主要提供对Controller层的功能支持
 * @author:AKS
 */
public interface SendMessageService {
    /**
     * 根据 UserId 发送信息给指定用户
     * @param message 消息内容
     */
    void sendMsgToUserByUserId(Message message);

    /**
     * 给所有在线用户发送消息
     * @param message 消息内容
     */
    void sendMsgToGroup(Message message);
}

SendMessageServiceImpl

package com.demo.netty.service.impl;

import com.demo.netty.config.NettyConfig;
import com.demo.netty.entity.Message;
import com.demo.netty.service.SendMessageService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author:AKS
 */
@Slf4j
@Service
public class SendMessageServiceImpl implements SendMessageService {
    /**
     *  根据 UserId 发送信息给指定用户
     */
    @Override
    public void sendMsgToUserByUserId(Message message) {
        // 根据userId获取对应的Channel
        Channel channel = NettyConfig.getOnlineUserChannelMap().get(message.getReceiver());
        if(Objects.isNull(channel)){
            throw new RuntimeException("UserId:" + message.getReceiver() + "不存在");
        }
        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(message.getUserId() + ":" + message.getMsg());
        // 将消息发送给指定用户
        channel.writeAndFlush(textWebSocketFrame);
    }
    /**
     * 给所有在线用户发送消息
     */
    @Override
    public void sendMsgToGroup(Message message) {
        NettyConfig.getOnlineChannelGroup().writeAndFlush(new TextWebSocketFrame(message.getMsg()));
    }
}

控制层Controller

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
postman测试,先让Mike通过websocket接口上线,然后用http请求发送消息来进行测试
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值