您好,登錄后才能下訂單哦!
小編給大家分享一下SpringBoot中如何使用WebSocket實(shí)現(xiàn)點(diǎn)對(duì)點(diǎn)消息,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
Spring 提供了 SimpMessagingTemplate 類來(lái)讓開(kāi)發(fā)者更加靈活地發(fā)送消息。使用 SimpMessagingTemplate,我們不僅可以在任意地方發(fā)送消息到 broker,也可以發(fā)送消息給某一個(gè)用戶,即點(diǎn)對(duì)點(diǎn)的消息發(fā)送。
這里我們編寫開(kāi)發(fā)用戶登錄的代碼了,直接使用 Spring Security 的用戶登錄機(jī)制和配置用戶。
一、添加依賴,配置
使用 Spring Security 里的用戶。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
我們現(xiàn)在需要配置用戶信息和權(quán)限配置。
@Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // 指定密碼的加密方式 @SuppressWarnings("deprecation") @Bean PasswordEncoder passwordEncoder(){ // 不對(duì)密碼進(jìn)行加密 return NoOpPasswordEncoder.getInstance(); } // 配置用戶及其對(duì)應(yīng)的角色 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("123").roles("ADMIN","USER") .and() .withUser("hangge").password("123").roles("USER"); } // 配置 URL 訪問(wèn)權(quán)限 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // 開(kāi)啟 HttpSecurity 配置 .anyRequest().authenticated() // 用戶訪問(wèn)所有地址都必須登錄認(rèn)證后訪問(wèn) .and().formLogin().permitAll(); // 開(kāi)啟表單登錄 } }
二、編寫WebSocket 配置
@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { // 設(shè)置消息代理的前綴,如果消息的前綴為"/queue",就會(huì)將消息轉(zhuǎn)發(fā)給消息代理(broker) // 再由消息代理廣播給當(dāng)前連接的客戶端 //也可設(shè)置多個(gè) broker,如:config.enableSimpleBroker("/topic","/queue"); config.enableSimpleBroker("/queue"); // 下面方法可以配置一個(gè)或多個(gè)前綴,通過(guò)這些前綴過(guò)濾出需要被注解方法處理的消息。 // 例如這里表示前綴為"/app"的destination可以通過(guò)@MessageMapping注解的方法處理 // 而其他 destination(例如"/topic""/queue")將被直接交給 broker 處理 config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { // 定義一個(gè)前綴為"/chart"的endpoint,并開(kāi)啟 sockjs 支持。 // sockjs 可以解決瀏覽器對(duì)WebSocket的兼容性問(wèn)題,客戶端將通過(guò)這里配置的URL建立WebSocket連接 registry.addEndpoint("/chat").withSockJS(); } }
三、編寫案例代碼
1、編寫實(shí)體
@Data public class Chat { // 消息的目標(biāo)用戶 private String to; // 消息的來(lái)源用戶 private String from; // 消息的主體內(nèi)容 private String content; }
2、編寫Controller
@Controller public class DemoController { @Autowired SimpMessagingTemplate messagingTemplate; // 處理來(lái)自"/app/chat"路徑的消息 @MessageMapping("/chat") public void chat(Principal principal, Chat chat) { // 獲取當(dāng)前登錄用戶的用戶名 String from = principal.getName(); // 將用戶設(shè)置給chat對(duì)象的from屬性 chat.setFrom(from); // 再將消息發(fā)送出去,發(fā)送的目標(biāo)用戶就是 chat 對(duì)象的to屬性值 messagingTemplate.convertAndSendToUser(chat.getTo(), "/queue/chat", chat); } }
四、編寫頁(yè)面
在 resources/static 目錄下創(chuàng)建 chat2.html 頁(yè)面作為點(diǎn)對(duì)點(diǎn)的聊天頁(yè)面。
連接成功后,訂閱的地址為“/user/queue/chat”,該地址比服務(wù)端配置的地址多了“/user”前綴,這是因?yàn)?SimpMessagingTemplate 類中自動(dòng)添加了路徑前綴。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>單聊</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.1.2/sockjs.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script> <script> var stompClient = null; // 建立一個(gè)WebSocket連接 function connect() { // 首先使用 SockJS 建立連接 var socket = new SockJS('/chat'); // 然后創(chuàng)建一個(gè)STOMP實(shí)例發(fā)起連接請(qǐng)求 stompClient = Stomp.over(socket); // 連接成功回調(diào) stompClient.connect({}, function (frame) { // 訂閱服務(wù)端發(fā)送回來(lái)的消息 stompClient.subscribe('/user/queue/chat', function (chat) { // 將服務(wù)端發(fā)送回來(lái)的消息展示出來(lái) showGreeting(JSON.parse(chat.body)); }); }); } // 發(fā)送消息 function sendMsg() { stompClient.send("/app/chat", {}, JSON.stringify({'content':$("#content").val(), 'to':$("#to").val()})); } // 將服務(wù)端發(fā)送回來(lái)的消息展示出來(lái) function showGreeting(message) { $("#chatsContent") .append("<div>" + message.from+":"+message.content + "</div>"); } // 頁(yè)面加載后進(jìn)行初始化動(dòng)作 $(function () { // 頁(yè)面加載完畢后自動(dòng)連接 connect(); $( "#send" ).click(function() { sendMsg(); }); }); </script> </head> <body> <div id="chat"> <div id="chatsContent"> </div> <div> 請(qǐng)輸入聊天內(nèi)容: <input type="text" id="content" placeholder="聊天內(nèi)容"> 目標(biāo)用戶: <input type="text" id="to" placeholder="目標(biāo)用戶"> <button id="send" type="button">發(fā)送</button> </div> </div> </body> </html>
五、驗(yàn)證結(jié)果
我們使用了 Spring Security 會(huì)自動(dòng)跳轉(zhuǎn)到默認(rèn)登錄頁(yè)面。
這里我們配置兩個(gè)用戶信息:admin/123,piao/123。
以上是“SpringBoot中如何使用WebSocket實(shí)現(xiàn)點(diǎn)對(duì)點(diǎn)消息”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。