在线聊天室的消息群聊的实现——springboot整合WebSocket(一)

一、创建项目

在这里插入图片描述

二、添加依赖

此处添加的是前端的依赖,为得是方便管理文件,不用在引用大量的js文件。
Maven搜索网址

在这里插入图片描述

<!-- https://mvnrepository.com/artifact/org.webjars/sockjs-client -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>sockjs-client</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.webjars/jquery -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.webjars/stomp-websocket -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>stomp-websocket</artifactId>
            <version>2.3.3-1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.webjars/webjars-locator-core -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
        </dependency>

三、添加配置类

在这里插入图片描述

package com.tony.websocket.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: WebSocketConfig
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/05/20:21
 * @Description: 配置类
 */
@Configuration
@EnableWebSocketMessageBroker   //开启websocket消息代理
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    /**
    * @Description: configureMessageBroker 配置消息代理
    * @Param: [registry]
    * @return: void
    * @Author: 皮蛋布丁
    * @Date: 2021/7/5 20:25
    */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //前缀为/topic的消息时,就将此消息转发给websocket代理,然后消息代理将消息转发给客户端
        registry.enableSimpleBroker("/topic");
        // 前缀为/app的消息,就被代理处理
        // 配置一个或多个前缀,通过这些前缀过滤取要被具体的方法处理的消息
        registry.setApplicationDestinationPrefixes("/app");
    }

    /**
    * @Description: registerStompEndpoints 注册连接点
    * @Param: [registry]
    * @return: void
    * @Author: 皮蛋布丁
    * @Date: 2021/7/5 20:33
    */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("chat").withSockJS();
    }
}

四、消息对象封装

在这里插入图片描述

package com.tony.websocket.bean;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: Message
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/05/20:37
 * @Description: 消息对象
 */
public class Message {

    private String name;

    private String content;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

五、添加controller

方式1

在这里插入图片描述

package com.tony.websocket.controller;

import com.tony.websocket.bean.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: GreetingController
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/05/20:35
 * @Description:
 */
@Controller
public class GreetingController {

    @MessageMapping("/hello")   //greeting方法用来处理浏览器发送过来的消息,消息则往/hello这里发送
    @SendTo("/topic/greetings")    //消息在greeting方法中处理完成后,消息转发到/greetings
    public Message greeting(Message message) {
        return message;
    }
}

方式2

在这里插入图片描述

package com.tony.websocket.controller;

import com.tony.websocket.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: GreetingController
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/05/20:35
 * @Description:
 */
@Controller
public class GreetingController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;    //消息发送模板

    /**
    * @Description: greeting 群聊的实现(方式2)
    * @Param: [message]
    * @return: void
    * @Author: 皮蛋布丁
    * @Date: 2021/7/5 22:07
    */
    @MessageMapping("/hello")
    public void greeting(Message message) {
        simpMessagingTemplate.convertAndSend("/topic/greetings",message);
    }
}

六、构建聊天界面

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>皮蛋布丁的聊天室</title>
    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
</head>
<body>
    <table>
        <tr>
            <td>请输入用户名:</td>
            <td><input type="text" id="name"></td>
        </tr>
        <tr>
            <td><input type="button" id="connect" value="连接"></td>
<!--            disabled="disabled":默认不可点击-->
            <td><input type="button" id="disconnect" disabled="disabled" value="断开连接"></td>
        </tr>
    </table>

<!--聊天界面-->
<div id="chat" style="display: none">
    <table>
        <tr>
            <td>请输入聊天内容</td>
            <td><input type="text" id="content"></td>
            <td><input type="button" id="send" value="发送"></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>

<!--    展示聊天内容-->
    <div id="conversation">群聊进行中...</div>
</div>
<script>
<!--    定义连接方法-->
    $(function () {
        //连接按钮事件
        $("#connect").click(function () {
            connect();
        })

        //断开连接按钮事件
        $("#disconnect").click(function () {
            if (stompClient != null) {
                //断开连接
                stompClient.disconnect();
            }
            //恢复按钮状态
            setConnection(false);
        })

        //发送按钮点击事件
        $("#send").click(function () {
            //发送消息(参数1:发送地址;参数2:消息优先级;参数3:JSON消息对象)
            stompClient.send('/app/hello',{},JSON.stringify({'name':$('#name').val(),'content':$('#content').val()}))
        })
    })

    var stompClient = null;

    function connect() {
        //判断是否输入用户名
        if (!$("#name").val()) {
            return;
        }
        //建立连接
        var socket = new SockJS('/chat');
        stompClient = Stomp.over(socket);
        //参数1:建立优先级;参数2:连接成功的回调;参数3:连接失败的回调
        stompClient.connect({},function (success) {
            //设置按钮状态
            setConnection(true);
            //订阅服务器上的消息
            //参数1:服务器上的地址;参数2:服务器收到的消息
            stompClient.subscribe('/topic/greetings',function (msg) {
                showGreeting(JSON.parse(msg.body));
            })
        })
    }

    function setConnection(flag) {
        //参数1:属性;参数2:设置状态
        $("#connect").prop("disabled",flag);
        $("#disconnect").prop("disabled",!flag);
        //显示div
        if (flag) {
            $("#chat").show();  //显示
        } else {
            $("#chat").hide();  //隐藏
        }
    }

    function showGreeting(msg) {
        $("#conversation").append('<div>' + msg.name + ';' + msg.content + '</div>');
    }
    
</script>

</body>
</html>

七、运行

1、建立连接

在这里插入图片描述

2、多用户聊天

在这里插入图片描述
在线聊天室的消息单聊的实现——springboot整合WebSocket(二)


注:能力有限,还请谅解,争取早日能够写出有质量的文章!

我是皮蛋布丁,一位爱吃皮蛋的热爱运动的废铁程序猿。

在这里插入图片描述

感谢各位大佬光临寒舍~

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值