SpringBoot WebSocket Stomp

关注 “弋凡”(YiFan)微信公众号吧 记录简单笔记 做你的最爱

websocket 是什么?

是一种网络通信协议,很多高级功能都需要它

为什么要使用websocket?

已经有了HTTP协议 为撒还需要使用WebSocket 嘞?

HTTP 是客户端请求服务端响应数据,但是我们如果想服务端给客户端发送消息嘞?

于是乎就有了这种协议,客户端,服务端可以双向发送消息

最典型的就是聊天系统

stomp

stomp 既 Simple (or Streaming) Text Orientated Messaging Protocol

简单(流)文本定向消息协议

为什么需要stomp?

常规的websocket连接和普通的TCP基本上没区别

所以STOMP在websocket上提供了一中基于帧线路格式(frame-based wire format)

简单一点,就是在我们的websocket(TCP)上面加了一层协议,使双方遵循这种协议来发送消息
在这里插入图片描述
服务端:/app,这里访问服务端,前缀通过设定的方式访问

用户:/user,这里针对的是用户消息的传递,针对于当前用户进行传递。

其他消息:/topic、/queue,这两种方式。都是定义出来用于订阅服务端

SpringBoot WebSocket 案例

导入pom依赖

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

websocket配置 - WebSocketConfig

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;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    // 基于STOMP协议的WebSocket

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册一个websocket端点,客户端将使用它连接到我们的websocket服务器。
        registry.addEndpoint("/socket").setAllowedOrigins("*").withSockJS();
    }
    
    // 注册相关服务
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //定义了服务端接收地址的前缀,也即客户端给服务端发消息的地址前缀
        registry.setApplicationDestinationPrefixes("/yifan");
        //定义了一个(或多个)客户端订阅地址的前缀信息,也就是客户端接收服务端发送消息的前缀信息
        registry.enableSimpleBroker("/topic","/user");
        // 点对点使用的订阅前缀(客户端订阅路径上会体现出来),不设置的话,默认也是/user/
        registry.setUserDestinationPrefix("/user/");
    }
}

服务端 controller

@Controller
@RequestMapping("yifan")
public class ChatController {

    @Autowired
    private SocketService socketService;

    /* 接收消息     @SendToUser 谁发送的返回给谁  */
    @MessageMapping("/chat")
    public void broadCast(SocketMessage message){
        socketService.sendToMsg(message);
    }

    /* 发送给个人*/
    @MessageMapping("/chatTo")
    public void serverSendUesrMsg(SocketMessage message){
        socketService.sendToUserMsg(message);
    }
}

客户端 网页

需要准备

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no" name="viewport">
    <title>YF 频道</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/mycss.css">
</head>
<body>

<div style="background: #6777ef;width: 100vw ;height: 100px;text-align: center;  margin-bottom: 50px;">
    <p style="font-weight: bold;color: white;font-size: 24px;  padding-top: 15px  ">YFTOOLS</p>
    <input type="hidden" th:value="${session.user.uname}" class="uname">
    <div class="container tools-top-page">弋凡 聊天频道 </div>
</div>

<div class="container" id="app">
    <div class="row" style="border: 1px solid #000000">
        <div class="col col-sm-8" id="msg" style="border-right: 2px solid #6777ef;height: 500px;overflow:auto; " ></div>
        <div class="col col-sm-4">
            <ul id="ras">
                <li  v-for="(item,i) in users"><input type="radio" :value="item.uname" name="redio"> {{item.uname}}</li>
            </ul>
        </div>
    </div>
    <div class="row">
        <div class="col-8">
            <textarea class="form-control" id="texts"style="position: absolute;left: 0px"></textarea>
        </div>
        <div class="col-4">
            <button class="btn btn-info one">个人</button>
            <button class="btn btn-info all">群发</button>
        </div>
    </div>
</div>
</body>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="/js/chat/sockjs.min.js"></script>
<script src="/js/chat/stomp.js"></script>
<script src="/js/vue.min.js"></script>
<script src="/js/axios.min.js"></script>
<script>
    new Vue({
        el:'#app',
        data:{
            users:[],
        },
        mounted(){
            this.chat();
        },
        methods:{
            chat(){
                axios.get('/user/All').then(res=>{
                    this.users = res.data;
                })
            }
        }
    });

    var name ='';
    // 连接
    var socket = new SockJS("http://126.75.109.85:81/socket");
    stompClient = Stomp.over(socket);
    stompClient.connect( {}, function (frame) {
        //订阅广播
        stompClient.subscribe('/topic/message', function (res) {
            $("#msg").append("<p class='text-center' ><span>"+JSON.parse(res.body).name +"</span>" + "<span style='color: red'> (全体消息) : </span>" +  JSON.parse(res.body).message  +  " </p>");
        });

        // 个人  == > 接收的消息 (订阅自己)
        name = $(".uname").val();
        stompClient.subscribe('/user/'+name+'/ptp', function (res) {
            console.log(name+"---------");
            // showGreeting(JSON.parse(data.body).content);
            console.log("res => "+res);
            $("#msg").append(
              "  <div class='media text-left'> <img src='https://q4.qlogo.cn/g?b=qq&amp;[email protected]&amp;s=3?d=retro' alt='null'  class='rounded-circle mr-1' width='40px'>" +
                " <div class='media-body'><h5 class='mt-0'> "+JSON.parse(res.body).name+" </h5>"+JSON.parse(res.body).message +"</div>  </div>  "
            );
        });

    },function (error) {
        console.log('连接失败【' + error + '】');
    });

    // 断开连接
    $("#disconnect").click(function () {
        if (stompClient !== null) {
            stompClient.disconnect();
            alert('用户: '+name+'   ...断开连接...');
            $("#msg").html("");
        }
    });
    
    // 单个发送
    $(".one").click(function () {
        var info = {};
        info.toname = $('input:radio:checked').val();
        info.name = name ;
        info.message = $("#texts").val();
        info.date = "1212";
        if(info.toname != info.name && info.message != null && info.message!='' ){
            $("#msg").append(
                "  <div class='media text-right'>" +
                " <div class='media-body'><h5 class='mt-0'> "+ info.name+" </h5>"+info.message +"</div>  <img class='rounded-circle mr-1' width='40px' src='https://q4.qlogo.cn/g?b=qq&amp;[email protected]&amp;s=3?d=retro' alt='null'> </div>  "
            );
            stompClient.send("/yifan/chatTo", {}, JSON.stringify(info) );
        }else {
            alert("不能给自己发送消息,内容不能为空~")
        }
        clearText();

    });

    // 群发
    $(".all").click(function () {
        var info = {};
        info.name = name;
        info.message = $("#texts").val();
        info.date = "1212";
        stompClient.send("/yifan/chat", {}, JSON.stringify(info) );
        clearText();
    });

    // 清空输入框
    function clearText(){
        $("#texts").val("");
    }

    //窗口关闭时,关闭连接
    window.οnbefοreunlοad=function() {
        socket.close();
    };
    
</script>
</html>

效果图

在这里插入图片描述
end –

快来关注“弋凡”微信公众号吧

快来关注“弋凡”微信公众号把

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章