一篇文章帶你使用SpringBoot基于WebSocket的在線群聊實(shí)現(xiàn)
一、添加依賴

加入前端需要用到的依賴:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
</dependency>
二、配置 WebSocketConfig
@Configuration
//開(kāi)啟使用STOMP協(xié)議來(lái)傳輸基于代理的消息,Broker就是代理的意思
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/**
* 配置消息代理
* @param registry
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//定義消息代理的前綴
registry.enableSimpleBroker("/topic");
//配置一個(gè)或者多個(gè)前綴,過(guò)濾出需要代理方法處理的消息
registry.setApplicationDestinationPrefixes("/app");
}
/**
* 注冊(cè)STOMP協(xié)議的節(jié)點(diǎn),并指定映射的URL
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//注冊(cè)STOMP協(xié)議節(jié)點(diǎn),同時(shí)指定使用 SockJS 協(xié)議
registry.addEndpoint("/chat").withSockJS();
}
}
三、配置 Message 類
Message 類用來(lái)接收瀏覽器發(fā)送的信息
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;
}
}
四、配置控制器 GreetingController
@Controller
public class GreetingController {
/**
* 這個(gè)方法用來(lái)處理瀏覽器發(fā)送來(lái)的消息,對(duì)其進(jìn)行處理
* @param message
* @return
*/
//@MessageMapping 類似 @RequestMapping
@MessageMapping("/hello")
//處理完之后對(duì)其進(jìn)行轉(zhuǎn)發(fā)到 SendTo 中的路徑
@SendTo("/topic/greetings")
public Message greeting(Message message) {
return message;
}
}
這里也可以使用 SimpMessagingTemplate 來(lái)進(jìn)行設(shè)置:
@Controller
public class GreetingController {
@Autowired
SimpMessagingTemplate simpMessagingTemplate;
@MessageMapping("/hello")
public void greeting(Message message) {
simpMessagingTemplate.convertAndSend("/topic/greetings", message);
}
}
SimpMessagingTemplate這個(gè)類主要是實(shí)現(xiàn)向?yàn)g覽器發(fā)送消息的功能。
五、設(shè)置前端頁(yè)面 chat.html
<!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>請(qǐng)輸入用戶名</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td><input type="button" id="connect" value="連接"></td>
<td><input type="button" id="disconnect" disabled="disabled" value="斷開(kāi)連接"></td>
</tr>
</table>
<div id="chat" style="display: none">
<table>
<tr>
<td>請(qǐng)輸入聊天內(nèi)容</td>
<td><input type="text" id="content"></td>
<td><input type="button" id="send" value="發(fā)送"></td>
</tr>
</table>
<div id="conversation">群聊進(jìn)行中...</div>
</div>
<script>
$(function () {
$("#connect").click(function () {
connect();
})
$("#disconnect").click(function () {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
})
$("#send").click(function () {
//將消息發(fā)送到代理方法內(nèi)
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);
//建立連接
stompClient.connect({}, function (success) {
setConnected(true);
stompClient.subscribe('/topic/greetings', function (msg) {
//拿到輸入的消息內(nèi)容進(jìn)行展示
showGreeting(JSON.parse(msg.body));
});
})
}
//展示消息的內(nèi)容
function showGreeting(msg) {
$("#conversation").append('<div>' + msg.name + ':' + msg.content + '</div>');
}
//設(shè)置連接按鈕,已經(jīng)連接上則禁止,反之不禁止
function setConnected(flag) {
$("#connect").prop("disabled", flag);
$("#disconnect").prop("disabled", !flag);
//連接上,才顯示聊天區(qū)的內(nèi)容
if (flag) {
$("#chat").show();
} else {
$("#chat").hide();
}
}
</script>
</body>
</html>
六、登錄測(cè)試
打開(kāi)兩個(gè)瀏覽器,實(shí)現(xiàn)群聊功能:

到此這篇關(guān)于一篇文章帶你使用SpringBoot基于WebSocket的在線群聊實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot WebSocket在線群聊內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot的WebSocket實(shí)現(xiàn)單聊群聊
- SpringBoot集成WebSocket長(zhǎng)連接實(shí)際應(yīng)用詳解
- SpringBoot+WebSocket+Netty實(shí)現(xiàn)消息推送的示例代碼
- SpringBoot+Websocket實(shí)現(xiàn)一個(gè)簡(jiǎn)單的網(wǎng)頁(yè)聊天功能代碼
- SpringBoot webSocket實(shí)現(xiàn)發(fā)送廣播、點(diǎn)對(duì)點(diǎn)消息和Android接收
- springboot整合websocket實(shí)現(xiàn)群聊思路代碼詳解
相關(guān)文章
spring使用JavaConfig進(jìn)行配置的方法
這篇文章主要介紹了spring使用JavaConfig進(jìn)行配置的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-09-09
關(guān)于Java語(yǔ)法糖以及語(yǔ)法糖的原理和用法
IntelliJ?IDEA快速查詢maven依賴關(guān)系圖文教程
Mybatis如何自動(dòng)生成數(shù)據(jù)庫(kù)表結(jié)構(gòu)總結(jié)
Java實(shí)戰(zhàn)項(xiàng)目練習(xí)之球館在線預(yù)約系統(tǒng)的實(shí)現(xiàn)
SpringSecurity默認(rèn)登錄頁(yè)的使用示例教程

