SpringBoot的WebSocket實(shí)現(xiàn)單聊群聊
本文實(shí)例為大家分享了SpringBoot的WebSocket實(shí)現(xiàn)單聊群聊,供大家參考,具體內(nèi)容如下
說(shuō)在開(kāi)頭在HTTP協(xié)議中,所有的請(qǐng)求都是由客戶(hù)端發(fā)送給服務(wù)端,然后服務(wù)端發(fā)送請(qǐng)求要實(shí)現(xiàn)服務(wù)器向客戶(hù)端推送消息有幾種methods:
1、輪詢(xún)
大量無(wú)效請(qǐng)求,浪費(fèi)資源
2、長(zhǎng)輪詢(xún)
有新數(shù)據(jù)再推送,但這會(huì)導(dǎo)致連接超時(shí),有一定隱患
3、Applet和Flash
過(guò)時(shí),安全隱患,兼容性不好
消息群發(fā)創(chuàng)建新項(xiàng)目:
添加依賴(lài):
<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>
創(chuàng)建WebSocket配置類(lèi):WebSocketConfig
@Configuration@EnableWebSocketMessageBroker//注解開(kāi)啟webSocket消息代理public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { /** * 配置webSocket代理類(lèi) * @param registry */ @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker('/topic'); //代理消息的前綴 registry.setApplicationDestinationPrefixes('/app'); //處理消息的方法前綴 } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint('/chat').withSockJS(); //定義一個(gè)/chat前綴的endpioint,用來(lái)連接 }}
創(chuàng)建Bean
/** * 群消息類(lèi) */public class Message { private String name; private String content;//省略getter& setter}
定義controller的方法:
/** * MessageMapping接受前端發(fā)來(lái)的信息 * SendTo 發(fā)送給信息WebSocket消息代理,進(jìn)行廣播 * @param message 頁(yè)面發(fā)來(lái)的json數(shù)據(jù)封裝成自定義Bean * @return 返回的數(shù)據(jù)交給WebSocket進(jìn)行廣播 * @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='https://rkxy.com.cn/webjars/jquery/jquery.min.js'></script> <script src='https://rkxy.com.cn/webjars/sockjs-client/sockjs.min.js'></script> <script src='https://rkxy.com.cn/webjars/stomp-websocket/stomp.min.js'></script> <script> var stompClient = null; //點(diǎn)擊連接以后的頁(yè)面改變 function setConnected(connection) { $('#connect').prop('disable',connection); $('#disconnect').prop('disable',!connection); if (connection) { $('#conversation').show(); $('#chat').show(); } else { $('#conversation').hide(); $('#chat').hide(); } $('#greetings').html(''); } //點(diǎn)擊連接按鈕建立連接 function connect() { //如果用戶(hù)名為空直接跳出 if (!$('#name').val()) { return; } //創(chuàng)建SockJs實(shí)例,建立連接 var sockJS = new SockJS('/chat'); //創(chuàng)建stomp實(shí)例進(jìn)行發(fā)送連接 stompClient = Stomp.over(sockJS); stompClient.connect({}, function (frame) { setConnected(true); //訂閱服務(wù)端發(fā)來(lái)的信息 stompClient.subscribe('/topic/greetings', function (greeting) { //將消息轉(zhuǎn)化為json格式,調(diào)用方法展示 showGreeting(JSON.parse(greeting.body)); }); }); } //斷開(kāi)連接 function disconnect() { if (stompClient !== null) { stompClient.disconnect(); } setConnected(false); } //發(fā)送信息 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'>用戶(hù)名</label> <input type='text' placeholder='請(qǐng)輸入用戶(hù)名'></div><div> <button type='button'>連接</button> <button type='button'>斷開(kāi)連接</button></div><div style='display: none;'> <div> <label for='name'></label> <input type='text' placeholder='聊天內(nèi)容'> </div> <button type='button'>發(fā)送</button> <div id='greetings'> <div style='display: none;'>群聊進(jìn)行中</div> </div></div></body></html>私聊
既然是私聊,就要有對(duì)象目標(biāo),也是用戶(hù),可以用SpringSecurity引入所以添加額外依賴(lài):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>
配置SpringSecurity
@Configurationpublic 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(); }}
在原來(lái)的WebSocketConfig配置類(lèi)中修改:也就是多了一個(gè)代理消息前綴:'/queue'
@Configuration@EnableWebSocketMessageBroker//注解開(kāi)啟webSocket消息代理public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { /** * 配置webSocket代理類(lèi) * @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(); //定義一個(gè)/chat前綴的endpioint,用來(lái)連接 }}
創(chuàng)建Bean:
public class Chat { private String to; private String from; private String content;//省略getter& setter}
添加controller方法:
/** * 點(diǎn)對(duì)點(diǎn)發(fā)送信息 * @param principal 當(dāng)前用戶(hù)的信息 * @param chat 發(fā)送的信息 */ @MessageMapping('chat') public void chat(Principal principal, Chat chat) { //獲取當(dāng)前對(duì)象設(shè)置為信息源 String from = principal.getName(); chat.setFrom(from); //調(diào)用convertAndSendToUser('用戶(hù)名','路徑','內(nèi)容'); simpMessagingTemplate.convertAndSendToUser(chat.getTo(), '/queue/chat', chat); }
創(chuàng)建頁(yè)面:
<html lang='en'><head> <meta charset='UTF-8'> <title>Title</title> <script src='https://rkxy.com.cn/webjars/jquery/jquery.min.js'></script> <script src='https://rkxy.com.cn/webjars/sockjs-client/sockjs.min.js'></script> <script src='https://rkxy.com.cn/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> 請(qǐng)輸入聊天內(nèi)容 <input type='text' placeholder='聊天內(nèi)容'> <input type='text' placeholder='目標(biāo)用戶(hù)'> <button type='button' id='send'>發(fā)送</button> </div></div></body></html>
暫結(jié)!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析2. JAMon(Java Application Monitor)備忘記3. Spring security 自定義過(guò)濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)4. 學(xué)python最電腦配置有要求么5. Python TestSuite生成測(cè)試報(bào)告過(guò)程解析6. 基于python實(shí)現(xiàn)操作git過(guò)程代碼解析7. 增大python字體的方法步驟8. python使用QQ郵箱實(shí)現(xiàn)自動(dòng)發(fā)送郵件9. python中用Scrapy實(shí)現(xiàn)定時(shí)爬蟲(chóng)的實(shí)例講解10. Python 的 __str__ 和 __repr__ 方法對(duì)比
