• WebSocket实现简单聊天功能案例


    简介
    1、使用WebSocket实现的一个简单的聊天功能业务
    2、使用了SpringBoot的ApplicationEvent事件监听用来与业务解耦
    3、需要注意的是websocket的长连接默认会在1分钟后自动关闭,状态码为:1001,正常关闭状态码为:1000
    因此客户端要定义一个定时器反复向服务端发送心跳,保持处于活跃状态(本文并未去实现)
    4、当前版本使用的是JDK的WebSocket,后面可以改成SpringBoot的WebSocketHandler
    
    • 1
    • 2
    • 3
    • 4
    • 5
    文末附项目Gitee链接
    一、Maven的引入
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.bootgroupId>
    			<artifactId>spring-boot-starter-websocketartifactId>
    			<version>2.4.0version>
    		dependency>
    		<dependency>
    			<groupId>org.springframework.bootgroupId>
    			<artifactId>spring-boot-starter-thymeleafartifactId>
    		dependency>
    		<dependency>
    			<groupId>com.alibabagroupId>
    			<artifactId>fastjsonartifactId>
    		dependency>
    		<dependency>
    			<groupId>org.springframework.bootgroupId>
    			<artifactId>spring-boot-starter-webartifactId>
    		dependency>
    		<dependency>
    			<groupId>org.projectlombokgroupId>
    			<artifactId>lombokartifactId>
    		dependency>
    	dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    二、后端代码结构图

    在这里插入图片描述

    二(1)ApplicationEvent及监听
    package com.chat.simplechat.event;
    
    import com.chat.simplechat.entity.GiftBean;
    import lombok.Getter;
    import org.springframework.context.ApplicationEvent;
    
    /**
     * 送礼物事件
     */
    @Getter
    public class GiftEvent extends ApplicationEvent {
    
        private GiftBean giftBean;
        
        public GiftEvent(Object source,GiftBean giftBean) {
            super(source);
            this.giftBean = giftBean;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    package com.chat.simplechat.event;
    
    import com.alibaba.fastjson.JSONObject;
    import com.chat.simplechat.entity.GiftBean;
    import com.chat.simplechat.websocket.WebSocket;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.event.EventListener;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.Resource;
    import java.util.Random;
    
    /**
     * 送礼物事件监听
     */
    @Slf4j
    @Component
    public class GiftEventListener {
        
        @Resource
        private WebSocket webSocket;
        
        @EventListener
        public void givingGifts(GiftEvent giftEvent){
            GiftBean giftBean = giftEvent.getGiftBean();
            Random random = new Random();
            String[] str = new String[]{"烟花","跑车","皇冠","凤冠","穿云箭"};
            int i = random.nextInt(str.length);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("fromUserId",giftBean.getFromUserId());
            jsonObject.put("toUserId",giftBean.getToUserId());
            jsonObject.put("contentText",str[i]);
            webSocket.sendOneMessage(giftBean.getToUserId(),jsonObject.toJSONString());
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    二(2)WebSocket及配置
    package com.chat.simplechat.websocket;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;
    import org.springframework.util.StringUtils;
    
    import javax.websocket.*;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import java.util.Iterator;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.CopyOnWriteArraySet;
    
    /**
     * websocket通讯
     */
    @Slf4j
    @Component
    @ServerEndpoint("/websocket/{userId}")
    public class WebSocket {
        
        private Session session;
        
        private String userId;
    
        /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/
        private static int onlineCount = 0;
    
        /**
         * 记录
         */
        private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    
        /**
         * 记录当前登录用户的会话
         */
        private static ConcurrentHashMap<String,Session> sessionPool = new ConcurrentHashMap<>();
        
        @OnOpen
        public void onOpen(Session session, @PathParam("userId") String userId){
            this.session = session;
            this.userId = userId;
            boolean exists = false;
            Iterator<WebSocket> iterator = webSockets.iterator();
            log.info("iterator:{}",iterator.hasNext());
            while (iterator.hasNext()){
                WebSocket webSocket = iterator.next();
                if(webSocket.userId.equals(userId)){
                    exists = true;
                    break;
                }
            }
            if(exists){
                //先删除之前的,在加入现在的
                this.remove();
            }
            webSockets.add(this);
            sessionPool.put(userId,session);
            log.info("【WebSocket】用户["+this.userId+"]已上线,当前在线用户数量:"+webSockets.size());
            this.addOnlineCount();
        }
    
        @OnClose
        public void onClose(){
            try {
                this.remove();
                log.info("【WebSocket】用户["+this.userId+"]已下线,当前在线用户数量:"+webSockets.size());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        @OnMessage
        public void onMessage(String message){
            log.info("【WebSocket】收到客户端消息:"+message);
            if(StringUtils.hasText(message)){
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId",this.userId);
                String toUserId = jsonObject.getString("toUserId");
                Session session = sessionPool.get(toUserId);
                //传送给对应toUserId用户的websocket
                if(StringUtils.hasText(toUserId) && null != session){
                    session.getAsyncRemote().sendText(jsonObject.toJSONString());
                }else{
                    log.error("请求的userid:{}不在该服务器上",toUserId);
                    //否则不在这个服务器上,发送到mysql或者redis
                }
            }
        }
    
        @OnError
        public void onError(Session session,Throwable throwable){
            log.error("消息发送错误,原因:{}",throwable.getMessage());
        }
    
        /**
         * 单点消息单用户发送
         * @param userId
         * @param message
         */
        public void sendOneMessage(String userId,String message){
            try {
                Session session = sessionPool.get(userId);
                if(null != session && session.isOpen()){
                    session.getAsyncRemote().sendText(message);
                    log.info("消息发送成功!");
                }
            } catch (Exception e) {
                throw new RuntimeException("消息发送失败:",e);
            }
        }
    
        /**
         * 单点消息多用户发送
         * @param userIds
         * @param message
         */
        public void sendMoreMessage(String[] userIds,String message){
            for (String userId : userIds) {
                try {
                    Session session = sessionPool.get(userId);
                    if(null != session && session.isOpen()){
                        session.getAsyncRemote().sendText(message);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    
        /**
         * 广播轮询
         * @param message
         */
        public void radioBroadcast(String message){
            for (WebSocket webSocket : webSockets) {
                try {
                    if(webSocket.session.isOpen()){
                        webSocket.session.getAsyncRemote().sendText(message);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    
        /**
         * 消息发送
         * @param message
         */
        public void sendMessage(String message){
            this.session.getAsyncRemote().sendText(message);
        }
    
        /**
         * 移除用户
         */
        private void remove() {
            webSockets.remove(this);
            sessionPool.remove(userId);
            this.subOnlineCount();
        }
    
        public static synchronized int getOnlineCount(){
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount(){
            WebSocket.onlineCount++;
        }
    
        public static synchronized void subOnlineCount(){
            WebSocket.onlineCount--;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    package com.chat.simplechat.websocket;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    /**
     * 启用websocket功能
     */
    @Configuration
    public class WebSocketConfig {
    
        @Bean
        public ServerEndpointExporter serverEndpointExporter(){
            return new ServerEndpointExporter();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    二(3)控制器及实体类
    package com.chat.simplechat.controller;
    
    import com.chat.simplechat.entity.GiftBean;
    import com.chat.simplechat.event.GiftEvent;
    import org.springframework.context.ApplicationContext;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    /**
     * 控制器
     */
    @Controller
    @RequestMapping("/gift")
    public class GiftController {
        
        @Resource
        private ApplicationContext applicationContext;
        
        @ResponseBody
        @GetMapping("/randomGift")
        public String randomGift(GiftBean giftBean){
            applicationContext.publishEvent(new GiftEvent(this,giftBean));
            return "成功";
        }
    
        @GetMapping("/page")
        public String page(){
            return "websocket/SimpleChat";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    package com.chat.simplechat.entity;
    
    import lombok.Data;
    
    /**
     * 礼物bean
     * @author wangyabin
     * @date 2021/8/24 10:52
     */
    @Data
    public class GiftBean {
    
        /**
         * 发送者ID
         */
        private String fromUserId;
    
        /**
         * 接收者ID
         */
        private String toUserId;
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    三、建立HTML
    DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="utf-8">
        <title>简单聊天室title>
    head>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js">script>
    
    <script>
        $(function(){
            $("#div").hide();
            $(".on-line").hide();
        })
        var socket;
        function openSocket() {
            if(typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            }else{
                console.log("您的浏览器支持WebSocket");
                var socketUrl="http://localhost:7523/websocket/"+$("#userId").val();
                socketUrl=socketUrl.replace("https","ws").replace("http","ws");
                console.log(socketUrl);
                if(socket!=null){
                    socket.close();
                    socket=null;
                }
                socket = new WebSocket(socketUrl);
                //打开事件
                socket.onopen = function() {
                    console.log("websocket已打开");
                    $("#div").show();
                    $(".on-line").show();
                    $("#login").hide();
                    //socket.send("这是来自客户端的消息" + location.href + new Date());
                };
                //获得消息事件
                socket.onmessage = function(msg) {
                    console.log(msg);
                    if(msg.data == "连接成功"){
                        $("#sendMessage").css("color","green");
                    }else{
                        var user = JSON.parse(msg.data);
                        console.log(user);
                        $("#user").text("【"+user.fromUserId+"】的消息:");
                        $("#msg").empty();
                        $("#msg").text(user.contentText);
                    }
    
                    console.log(msg.data);
                    //发现消息进入    开始处理前端触发逻辑
                };
                //关闭事件
                socket.onclose = function() {
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                socket.onerror = function(e) {
                    console.log(e);
                    console.log("websocket发生了错误");
                }
            }
        }
        function sendMessage() {
            var msg = $("#contentText").val();
            $("#contentText").val("");
            console.log(msg);
            if(typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
                $("#msg").val("您的浏览器不支持WebSocket");
            }else {
                console.log("您的浏览器支持WebSocket");
                console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+msg+'"}');
                socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+msg+'"}');
            }
        }
        //送礼物
        function givingGifts(){
            $.ajax({
                url:'/gift/randomGift',
                post:'get',
                data:{"fromUserId":$("#userId").val(),"toUserId":$("#toUserId").val()},
                success:function(data){
                    console.log(data);
                },error:function(e){
                    console.log(e);
                }
            })
        }
    script>
    <body style="margin: 0;width: 100%;margin: auto">
    <div style="margin: 10% 50% 10% 25%;border: 1px solid #cefff4;padding:1% 2% 1% 2%;background-color: #cefff4">
        <div>
            <p><h1>无痕聊天室😳h1>p>
            <p style="padding-left: 70%" class="on-line">
                <span style="color: purple">在线span>|
                <span style="color: crimson;cursor: pointer" onclick="givingGifts()">送礼物span>
            p>
            <p><span id="gift">span>p>
        div>
        <div>
            <p>【😀】:
                <select id="userId">
                    <option value="S">Soption>
                    <option value="N">Noption>
                select>p>
            <p>【😄】:
                <select id="toUserId">
                    <option value="N">Noption>
                    <option value="S">Soption>
                select>
            p>
            <p><span id="user">span><span id="msg">span>p>
            <p> 
                <input id="contentText" name="contentText">
            p>
            <p><div id="div" style="margin-left: 70%"><button id="sendMessage" onclick="sendMessage()" style="cursor: pointer">发送消息button>div>
            <p style="padding-left: 70%"><button id="login" onclick="openSocket()" style="cursor: pointer">上线button>p>
        div>
    div>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    四、成功截图
    测试的时候只需要在网页中打开两个链接选择不同角色即可

    在这里插入图片描述

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

    五、改造后的目录和成功的截图

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

    六、说明
    改造后的工程将原先写死在页面的通讯用户改为登录后通知了(用户彼此之间并非好友关系,带改造)将原先JDK自带的WebSocket替换成了SpringBoot的WebSocketHandler
    同时引入了JWT令牌做登录用户凭证,加入了WebSocket建立通讯前的握手拦截,在拦截处校验了用户身份是否有效

    在这里插入图片描述

    伪造了Spring注册Bean的方式代替数据库存储的用户信息
    需要改造的地方还很多,前端使用了localStorage存储的token,用户信息持久化,用户间的关系持久化,客户端发送心跳,代码优化…
    (2022-11-07)优化后的效果

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

    目前只实现了聊天,送礼物等功能暂未实现
    
    • 1
    Gitee链接(改造后简聊)

    简聊

  • 相关阅读:
    软件工程师:机器学习也需要学习?
    【OpenCV】在Linux上使用OpenCvSharp
    嵌入式:驱动开发 Day2
    SAP SEGW 事物码里的 ABAP 类型和 EDM 类型映射的一个具体例子
    推荐几个好用的国内AI网站
    windows10提权
    muduo库的高性能日志库(一)
    128 只 LED 显示驱动芯片 CH457
    Java虚拟机
    【力扣】16. 最接近的三数之和
  • 原文地址:https://blog.csdn.net/cm777/article/details/127550730