您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在SpringBoot中利用WebSocket實現一個群聊功能,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
消息群發
創建新項目:
添加依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <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.3.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>
創建WebSocket配置類:WebSocketConfig
@Configuration @EnableWebSocketMessageBroker//注解開啟webSocket消息代理 public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { /** * 配置webSocket代理類 * @param registry */ @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); //代理消息的前綴 registry.setApplicationDestinationPrefixes("/app"); //處理消息的方法前綴 } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/chat").withSockJS(); //定義一個/chat前綴的endpioint,用來連接 } }
創建Bean
/** * 群消息類 */ public class Message { private String name; private String content; //省略getter& setter }
定義controller的方法:
/** * MessageMapping接受前端發來的信息 * SendTo 發送給信息WebSocket消息代理,進行廣播 * @param message 頁面發來的json數據封裝成自定義Bean * @return 返回的數據交給WebSocket進行廣播 * @throws Exception */ @MessageMapping("/hello") @SendTo("/topic/greetings") public Message greeting(Message message) throws Exception { return message; }
<html lang="en"> <head> <meta charset="UTF-8"> <title>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> <script> var stompClient = null; //點擊連接以后的頁面改變 function setConnected(connection) { $("#connect").prop("disable",connection); $("#disconnect").prop("disable",!connection); if (connection) { $("#conversation").show(); $("#chat").show(); } else { $("#conversation").hide(); $("#chat").hide(); } $("#greetings").html(""); } //點擊連接按鈕建立連接 function connect() { //如果用戶名為空直接跳出 if (!$("#name").val()) { return; } //創建SockJs實例,建立連接 var sockJS = new SockJS("/chat"); //創建stomp實例進行發送連接 stompClient = Stomp.over(sockJS); stompClient.connect({}, function (frame) { setConnected(true); //訂閱服務端發來的信息 stompClient.subscribe("/topic/greetings", function (greeting) { //將消息轉化為json格式,調用方法展示 showGreeting(JSON.parse(greeting.body)); }); }); } //斷開連接 function disconnect() { if (stompClient !== null) { stompClient.disconnect(); } setConnected(false); } //發送信息 function sendName() { stompClient.send("/app/hello",{},JSON.stringify({'name': $("#name").val() , 'content': $("#content").val()})); } //展示聊天房間 function showGreeting(message) { $("#greetings").append("<div>"+message.name + ":" + message.content + "</div>"); } $(function () { $("#connect").click(function () { connect(); }); $("#disconnect").click(function () { disconnect(); }); $("#send").click(function () { sendName(); }) }) </script> </head> <body> <div> <label for="name">用戶名</label> <input type="text" id="name" placeholder="請輸入用戶名"> </div> <div> <button id="connect" type="button">連接</button> <button id="disconnect" type="button">斷開連接</button> </div> <div id="chat" > <div> <label for="name"></label> <input type="text" id="content" placeholder="聊天內容"> </div> <button id="send" type="button">發送</button> <div id="greetings"> <div id="conversation" >群聊進行中</div> </div> </div> </body> </html>
既然是私聊,就要有對象目標,也是用戶,可以用SpringSecurity引入
所以添加額外依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
配置SpringSecurity
@Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("panlijie").roles("admin").password("$2a$10$5Pf0KhCdnrpMxP5aRrHvMOsvV2fvfWJqk0SEDa9vQ8OWwV8emLFhi") .and() .withUser("suyanxia").roles("user").password("$2a$10$5Pf0KhCdnrpMxP5aRrHvMOsvV2fvfWJqk0SEDa9vQ8OWwV8emLFhi"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .permitAll(); } }
在原來的WebSocketConfig配置類中修改:也就是多了一個代理消息前綴:"/queue"
@Configuration @EnableWebSocketMessageBroker//注解開啟webSocket消息代理 public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { /** * 配置webSocket代理類 * @param registry */ @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic","/queue"); //代理消息的前綴 registry.setApplicationDestinationPrefixes("/app"); //處理消息的方法前綴 } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/chat").withSockJS(); //定義一個/chat前綴的endpioint,用來連接 } }
創建Bean:
public class Chat { private String to; private String from; private String content; //省略getter& setter }
添加controller方法:
/** * 點對點發送信息 * @param principal 當前用戶的信息 * @param chat 發送的信息 */ @MessageMapping("chat") public void chat(Principal principal, Chat chat) { //獲取當前對象設置為信息源 String from = principal.getName(); chat.setFrom(from); //調用convertAndSendToUser("用戶名","路徑","內容"); simpMessagingTemplate.convertAndSendToUser(chat.getTo(), "/queue/chat", chat); }
創建頁面:
<html lang="en"> <head> <meta charset="UTF-8"> <title>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> <script> var stompClient = null; function connect() { var socket = new SockJS("/chat"); stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { stompClient.subscribe('/user/queue/chat', function (chat) { showGreeting(JSON.parse(chat.body)); }); }); } function sendMsg() { stompClient.send("/app/chat",{},JSON.stringify({'content' : $("#content").val(), 'to': $("#to").val()})); } function showGreeting(message) { $("#chatsContent").append("<div>" + message.from + ":" + message.content + "</div>"); } $(function () { connect(); $("#send").click(function () { sendMsg(); }); }); </script> </head> <body> <div id="chat"> <div id="chatsContent"> </div> <div> 請輸入聊天內容 <input type="text" id="content" placeholder="聊天內容"> <input type="text" id="to" placeholder="目標用戶"> <button type="button" id="send">發送</button> </div> </div> </body> </html>
上述內容就是怎么在SpringBoot中利用WebSocket實現一個群聊功能,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。