【SpringBoot学习】11、SpringBoot 整合 Websocket 实现聊天系统

【SpringBoot 学习】11、SpringBoot 整合 Websocket 实现聊天系统

websocket 最伟大之处在于服务器和客户端可以在给定的时间范围内的任意时刻,相互推送信息。 浏览器和服务器只需要要做一个握手的动作,在建立连接之后,服务器可以主动传送数据给客户端,客户端也可以随时向服务器发送数据。

实现功能:springboot 整合 websocket 实现一对一,多对多聊天系统

项目源码:https://github.com/Tellsea/springboot-learn/tree/master/springboot-websocket

支持作者就 Star Mua~

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

其他的还用到了thymeleaf,lombok,fastjson,自己加一下

配置类

/**
 * websocket的配置
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

WebSocket

@Slf4j
@Component
@ServerEndpoint("/websocket/{username}")
public class WebSocket {

    /**
     * 在线人数
     */
    public static int onlineNumber = 0;
    /**
     * 以用户的姓名为key,WebSocket为对象保存起来
     */
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    /**
     * 会话
     */
    private Session session;
    /**
     * 用户名称
     */
    private String username;

    /**
     * OnOpen 表示有浏览器链接过来的时候被调用
     * OnClose 表示浏览器发出关闭请求的时候被调用
     * OnMessage 表示浏览器发消息的时候被调用
     * OnError 表示有错误发生,比如网络断开了等等
     */

    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        onlineNumber++;
        log.info("现在来连接的客户id:" + session.getId() + "用户名:" + username);
        this.username = username;
        this.session = session;
        log.info("有新连接加入! 当前在线人数" + onlineNumber);
        try {
            //messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
            //先给所有人发送通知,说我上线了
            Map<String, Object> map1 = new HashMap<>();
            map1.put("messageType", 1);
            map1.put("username", username);
            sendMessageAll(JSON.toJSONString(map1), username);

            //把自己的信息加入到map当中去
            clients.put(username, this);
            //给自己发一条消息:告诉自己现在都有谁在线
            Map<String, Object> map2 = new HashMap<>();
            map2.put("messageType", 3);
            //移除掉自己
            Set<String> set = clients.keySet();
            map2.put("onlineUsers", set);
            sendMessageTo(JSON.toJSONString(map2), username);
        } catch (IOException e) {
            log.info(username + "上线的时候通知所有人发生了错误");
        }


    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.info("服务端发生了错误" + error.getMessage());
        //error.printStackTrace();
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        onlineNumber--;
        //webSockets.remove(this);
        clients.remove(username);
        try {
            //messageType 1代表上线 2代表下线 3代表在线名单  4代表普通消息
            Map<String, Object> map1 = new HashMap<>();
            map1.put("messageType", 2);
            map1.put("onlineUsers", clients.keySet());
            map1.put("username", username);
            sendMessageAll(JSON.toJSONString(map1), username);
        } catch (IOException e) {
            log.info(username + "下线的时候通知所有人发生了错误");
        }
        log.info("有连接关闭! 当前在线人数" + onlineNumber);
    }

    /**
     * 收到客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            log.info("来自客户端消息:" + message + "客户端的id是:" + session.getId());
            JSONObject jsonObject = JSON.parseObject(message);
            String textMessage = jsonObject.getString("message");
            String fromusername = jsonObject.getString("username");
            String tousername = jsonObject.getString("to");
            //如果不是发给所有,那么就发给某一个人
            //messageType 1代表上线 2代表下线 3代表在线名单  4代表普通消息
            Map<String, Object> map1 = new HashMap<>();
            map1.put("messageType", 4);
            map1.put("textMessage", textMessage);
            map1.put("fromusername", fromusername);
            if (tousername.equals("All")) {
                map1.put("tousername", "所有人");
                sendMessageAll(JSON.toJSONString(map1), fromusername);
            } else {
                map1.put("tousername", tousername);
                sendMessageTo(JSON.toJSONString(map1), tousername);
            }
        } catch (Exception e) {
            log.info("发生了错误了");
        }
    }

    public void sendMessageTo(String message, String ToUserName) throws IOException {
        for (WebSocket item : clients.values()) {
            if (item.username.equals(ToUserName)) {
                item.session.getAsyncRemote().sendText(message);
                break;
            }
        }
    }

    public void sendMessageAll(String message, String FromUserName) throws IOException {
        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineNumber;
    }

}

控制器

@Slf4j
@Controller
public class WebSocketController {

    @RequestMapping("/websocket/{name}")
    public String webSocket(@PathVariable String name, Model model) {
        try {
            log.info("跳转到websocket的页面上");
            model.addAttribute("username", name);
            return "websocket";
        } catch (Exception e) {
            log.info("跳转到websocket的页面上发生异常,异常信息是:" + e.getMessage());
            return "error";
        }
    }
}

html 页面

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>websocket</title>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
    <script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
</head>

<body>
<div style="margin: auto;text-align: center">
    <h1>Welcome to websocket</h1>
</div>
<br/>
<div style="margin: auto;text-align: center">
    <select id="onLineUser">
        <option>--所有--</option>
    </select>
    <input id="text" type="text"/>
    <button onclick="send()">发送消息</button>
</div>
<br>
<div style="margin-right: 10px;text-align: right">
    <button onclick="closeWebSocket()">关闭连接</button>
</div>
<hr/>
<div id="message" style="text-align: center;"></div>
<input type="text" th:value="${username}" id="username" style="display: none"/>
</body>


<script type="text/javascript">
    var webSocket;
    var commWebSocket;
    if ("WebSocket" in window) {
        webSocket = new WebSocket("ws://localhost:8080/websocket/" + document.getElementById('username').value);

        //连通之后的回调事件
        webSocket.onopen = function () {
            //webSocket.send( document.getElementById('username').value+"已经上线了");
            console.log("已经连通了websocket");
            setMessageInnerHTML("已经连通了websocket");
        };

        //接收后台服务端的消息
        webSocket.onmessage = function (evt) {
            var received_msg = evt.data;
            console.log("数据已接收:" + received_msg);
            var obj = JSON.parse(received_msg);
            console.log("可以解析成json:" + obj.messageType);
            //1代表上线 2代表下线 3代表在线名单 4代表普通消息
            if (obj.messageType == 1) {
                //把名称放入到selection当中供选择
                var onlineName = obj.username;
                var option = "<option>" + onlineName + "</option>";
                $("#onLineUser").append(option);
                setMessageInnerHTML(onlineName + "上线了");
            } else if (obj.messageType == 2) {
                $("#onLineUser").empty();
                var onlineName = obj.onlineUsers;
                var offlineName = obj.username;
                var option = "<option>" + "--所有--" + "</option>";
                for (var i = 0; i < onlineName.length; i++) {
                    if (!(onlineName[i] == document.getElementById('username').value)) {
                        option += "<option>" + onlineName[i] + "</option>"
                    }
                }
                $("#onLineUser").append(option);

                setMessageInnerHTML(offlineName + "下线了");
            } else if (obj.messageType == 3) {
                var onlineName = obj.onlineUsers;
                var option = null;
                for (var i = 0; i < onlineName.length; i++) {
                    if (!(onlineName[i] == document.getElementById('username').value)) {
                        option += "<option>" + onlineName[i] + "</option>"
                    }
                }
                $("#onLineUser").append(option);
                console.log("获取了在线的名单" + onlineName.toString());
            } else {
                setMessageInnerHTML(obj.fromusername + "对" + obj.tousername + "说:" + obj.textMessage);
            }
        };

        //连接关闭的回调事件
        webSocket.onclose = function () {
            console.log("连接已关闭...");
            setMessageInnerHTML("连接已经关闭....");
        };
    } else {
        // 浏览器不支持 WebSocket
        alert("您的浏览器不支持 WebSocket!");
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    function closeWebSocket() {
        //直接关闭websocket的连接
        webSocket.close();
    }

    function send() {
        var selectText = $("#onLineUser").find("option:selected").text();
        if (selectText == "--所有--") {
            selectText = "All";
        } else {
            setMessageInnerHTML(document.getElementById('username').value + "对" + selectText + "说:" + $("#text").val());
        }
        var message = {
            "message": document.getElementById('text').value,
            "username": document.getElementById('username').value,
            "to": selectText
        };
        webSocket.send(JSON.stringify(message));
        $("#text").val("");

    }
</script>

</html>

效果图

在这里插入图片描述

参考文章:https://blog.csdn.net/qq_38455201/article/details/80374712

微信公众号

在这个互联网时代,客服可以说必不可少,每个电商网站都应该有一个强大的智能客服对话系统,以满足用户沟通的需求。智能客服对话系统,不仅需要人工的沟通,同时结合人工智能实现智能对话,减少人工客服的成本,势在必行。基于SpringBoot+Python的多语言前后端智能多人聊天系统课程,将以基础知识为根基,带大家完成一个强大的智能客服系统,该系统将包含以下功能:智能对话机器人、单聊、群聊、消息撤回、上线、下线通知、用户动态信息实时提示等。即时通讯和人工智能,在未来的发展趋势,必然需要大批人才,掌握这两个技术势在必行。项目是一个真实可用的项目,商业价值不言而喻。也可以基于课程的基础上进一步完善和优化,所以价值是很高的。本课程包含的技术: 开发工具为:IDEA、WebStorm、PyCharmTensorflowRNNLSTMAnacondaSpringBoot SpringCloudWebsocketSTOMPDjangoVue+Nodejs+jQuery等 课程亮点: 1.与企业接轨、真实工业界产品2.从基础到案例,逐层深入,学完即用3.市场主流的前后端分离架构和人工智能应用结合开发4.多语言结合开发,满足多元化的需求5.涵盖TensorFlow1.x+TensorFlow2.x版本6.智能机器人实战7.即时通讯实战8.多Python环境切换9.微服务SpringBoot10.集成SpringCloud实现统一整合方案 11.全程代码实操,提供全部代码和资料 12.提供答疑和提供企业技术方案咨询 课程目录:第一章、Anaconda以及TensorFlow环境和使用0、智能多人聊天系统课程说明1、智能多人聊天系统之Anaconda讲解2、智能多人聊天系统之Anaconda安装和使用3、智能多人聊天系统之Anaconda之conda命令使用4、智能多人聊天系统之TensorFlow讲解5、智能多人聊天系统之TensorFlow安装和使用6、TensorFlow常量、变量和占位符实战讲解17、TensorFlow常量、变量和占位符实战讲解28、TensorFlow原理补充讲解9、TensorFlow四则运算实战讲10、TensorFlow矩阵操作以及运算实战讲解111、TensorFlow矩阵操作以及运算实战讲解212、TensorFlow均匀分布和正态分布数据实战讲解13、智能多人聊天系统之Numpy实战讲解14、智能多人聊天系统之matplotlib实战讲解15、TensorFlow深度学习DNN讲解16、TensorFlow常用Python扩展包讲解17、TensorFlow常用回归算法以及正则化讲解18、TensorFlow损失函数定义和使用实战讲解19、TensorFlow优化器讲解以及综合案例实战讲解20、智能多人聊天系统之RNN讲解21、智能多人聊天系统之RNN种类讲解22、智能多人聊天系统之RNN代码实战23、智能多人聊天系统之LSTM讲解24、智能多人聊天系统之attention机制讲解25、智能多人聊天系统之Django环境构建及初体验26、智能多人聊天系统之Django开发27、Python章节环境侯建和项目搭建28、Python TensorFlow读取训练数据代码编写29、Python TensorFlow形成语料编码30、Python TensorFlow保存字典文件31、Python TensorFlow构建词向量32、Python TensorFlow构建lstm模型以及attention wrapper33、Python TensorFlow训练代码编写34、Python整体代码讲解35、Python运用模型代码讲解36、SpringBoot讲解以及构建web应用37、Spring Cloud注册中心构建38、智能多人聊天系统之前端Vue项目构建39、SpringBoot+Websocket群聊40、SpringBoot+Websocket昵称群聊41、SpringBoot+Websocket群聊+单聊实战42、SpringBoot+Stomp单聊143、SpringBoot+Stomp单聊244、SpringBoot+Stomp单聊+群聊45、Django Web整合TF代码讲解及Postman调试46、智能客服系统单聊群聊等项目功能代码讲解147、智能客服系统单聊群聊等项目功能代码讲解248、智能客服系统集成机器人对话代码开发讲解49、智能机器人TensorFlow2版本升级实战之训练模型代码讲解50、智能机器人TensorFlow2版本升级实战之预测代码讲解 51、智能机器人TensorFlow2版本升级实战补充讲解
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tellsea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值