WebSocket 结合Springboot +maven 教程

实现的最终效果

在这里插入图片描述

1.websocket原理

在这里插入图片描述
前端通过订阅 相应的URL。
在这里插入图片描述

js 代码部分

var stompClient = null;

function setConnected(connected) {
$("#connect").prop(“disabled”, connected);
$("#disconnect").prop(“disabled”, !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#notice").html("");
}

function connect() {
var socket = new SockJS(’/endpoint-websocket’);
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ’ + frame);

    //订阅群聊消息
    stompClient.subscribe('/topic/chat', function (result) {
    	showContent(JSON.parse(result.body));
    });
    
    //订阅在线用户消息
    stompClient.subscribe('/topic/onlineuser', function (result) {
    	showOnlieUser(JSON.parse(result.body));
    });
    
    
});

}

//断开连接
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log(“Disconnected”);
}

//发送聊天记录
function sendContent() {
stompClient.send("/app/v6/chat", {}, JSON.stringify({‘content’: $("#content").val()}));

}

//显示聊天记录
function showContent(body) {
$("#record").append("" + body.content + " “+new Date(body.time).toLocaleTimeString()+”");
}

//显示实时在线用户
function showOnlieUser(body) {
$("#online").html("" + body.content + " “+new Date(body.time).toLocaleTimeString()+”");
}

扫描二维码关注公众号,回复: 5560634 查看本文章

$(function () {

connect();//自动上线

$("form").on('submit', function (e) {
    e.preventDefault();
});
 
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() {
	sendContent(); 
});

});

2.后端必不可少的webstocket配置

在这里插入图片描述
前端发送的通过js函数
在这里插入图片描述
前端接收

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

后端接收
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq892628217/article/details/87909010
今日推荐