本篇內(nèi)容介紹了“SpringBoot中怎么使用WebSocket實(shí)現(xiàn)點(diǎn)對點(diǎn)消息”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
專注于為中小企業(yè)提供成都網(wǎng)站建設(shè)、網(wǎng)站建設(shè)服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)東昌府免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了成百上千企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
一、添加依賴,配置
使用 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(){ // 不對密碼進(jìn)行加密 return NoOpPasswordEncoder.getInstance(); } // 配置用戶及其對應(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 訪問權(quán)限 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() // 開啟 HttpSecurity 配置 .anyRequest().authenticated() // 用戶訪問所有地址都必須登錄認(rèn)證后訪問 .and().formLogin().permitAll(); // 開啟表單登錄 } }
二、編寫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è)前綴,通過這些前綴過濾出需要被注解方法處理的消息。 // 例如這里表示前綴為"/app"的destination可以通過@MessageMapping注解的方法處理 // 而其他 destination(例如"/topic""/queue")將被直接交給 broker 處理 config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { // 定義一個(gè)前綴為"/chart"的endpoint,并開啟 sockjs 支持。 // sockjs 可以解決瀏覽器對WebSocket的兼容性問題,客戶端將通過這里配置的URL建立WebSocket連接 registry.addEndpoint("/chat").withSockJS(); } }
三、編寫案例代碼
1、編寫實(shí)體
@Data public class Chat { // 消息的目標(biāo)用戶 private String to; // 消息的來源用戶 private String from; // 消息的主體內(nèi)容 private String content; }
2、編寫Controller
@Controller public class DemoController { @Autowired SimpMessagingTemplate messagingTemplate; // 處理來自"/app/chat"路徑的消息 @MessageMapping("/chat") public void chat(Principal principal, Chat chat) { // 獲取當(dāng)前登錄用戶的用戶名 String from = principal.getName(); // 將用戶設(shè)置給chat對象的from屬性 chat.setFrom(from); // 再將消息發(fā)送出去,發(fā)送的目標(biāo)用戶就是 chat 對象的to屬性值 messagingTemplate.convertAndSendToUser(chat.getTo(), "/queue/chat", chat); } }
四、編寫頁面
在 resources/static 目錄下創(chuàng)建 chat2.html 頁面作為點(diǎn)對點(diǎn)的聊天頁面。
連接成功后,訂閱的地址為“/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ā)起連接請求 stompClient = Stomp.over(socket); // 連接成功回調(diào) stompClient.connect({}, function (frame) { // 訂閱服務(wù)端發(fā)送回來的消息 stompClient.subscribe('/user/queue/chat', function (chat) { // 將服務(wù)端發(fā)送回來的消息展示出來 showGreeting(JSON.parse(chat.body)); }); }); } // 發(fā)送消息 function sendMsg() { stompClient.send("/app/chat", {}, JSON.stringify({'content':$("#content").val(), 'to':$("#to").val()})); } // 將服務(wù)端發(fā)送回來的消息展示出來 function showGreeting(message) { $("#chatsContent") .append("<div>" + message.from+":"+message.content + "</div>"); } // 頁面加載后進(jìn)行初始化動(dòng)作 $(function () { // 頁面加載完畢后自動(dòng)連接 connect(); $( "#send" ).click(function() { sendMsg(); }); }); </script> </head> <body> <div id="chat"> <div id="chatsContent"> </div> <div> 請輸入聊天內(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)登錄頁面。
這里我們配置兩個(gè)用戶信息:admin/123,piao/123。
“SpringBoot中怎么使用WebSocket實(shí)現(xiàn)點(diǎn)對點(diǎn)消息”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
文章標(biāo)題:SpringBoot中怎么使用WebSocket實(shí)現(xiàn)點(diǎn)對點(diǎn)消息
文章來源:http://jinyejixie.com/article46/iepehg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、網(wǎng)站排名、靜態(tài)網(wǎng)站、網(wǎng)站策劃、網(wǎng)站設(shè)計(jì)、域名注冊
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)