


版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、springboot中使用 websocket簡單例子gradle中添加依賴,引入websocket支持compile("org.springframework.boot:spring-boot-starter-websocket:$springBootVersion")啟用 websocketpackage cn.xiaojf.today.ws.configuration;importcn.xiaojf.today.ws.handler.CountWebSocketHandler;erceptor.Handshake
2、Interceptor;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.socket.config.annotation.EnableWebSocket;importorg.springframework.web.socket.config.annotatio
3、n.WebSocketConfigurer;importorg.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;importorg.springframework.web.socket.server.standard.ServerEndpointExporter;/* websocket 配置* author xiaojf 2017/3/2 9:50.*/ConfigurationEnableWebSocketpublic class WebSocketConfig implements WebSock
4、etConfigurer Beanpublic ServerEndpointExporterserverEndpointExporter(ApplicationContext context) return new ServerEndpointExporter();Overridepublic voidregisterWebSocketHandlers(WebSocketHandlerRegistryregistry) registry.addHandler(newCountWebSocketHandler(),"/web/count").addInterceptors(n
5、ewHandshakeInterceptor();消息攔截處理package erceptor;importorg.springframework.http.server.ServerHttpRequest;importorg.springframework.http.server.ServerHttpResponse;importorg.springframework.web.socket.WebSocketHandler;importorg.springframework.web.socket.server.support.HttpSession
6、HandshakeInterceptor;import java.util.Map;/* 消息攔截處理類* author xiaojf 2017/3/2 10:36.*/public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor Overridepublic boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,Map<String,O
7、bject> attributes) throws Exception /解決 The extension x-webkit-deflate-frame is not supported 問題if(request.getHeaders().containsKey("Sec-WebSocket-Exte nsions") request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");System.out.println("Be
8、fore Handshake");return super.beforeHandshake(request, response, wsHandler, attributes);Overridepublic void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,Exception ex) System.out.println("After Handshake");super.afterHandshake(reques
9、t, response,wsHandler, ex);消息處理相應(yīng)類package cn.xiaojf.today.ws.handler;import com.alibaba.druid.support.json.JSONUtils;import mons.collections.map.HashedMap;import org.springframework.stereotype.Component;import org.springframework.web.socket.CloseStatus;import org.springframework.web.socket.TextMessa
10、ge;importorg.springframework.web.socket.WebSocketSession;importorg.springframework.web.socket.handler.TextWebSocketHandler;import java.io.IOException;import java.util.*;/* author xiaojf 2017/3/2 9:55.*/Componentpublic class CountWebSocketHandler extends TextWebSocketHandler private static long count
11、 = 0;private static Map<String,WebSocketSession> sessionMap = new HashedMap();Overrideprotected voidhandleTextMessage(WebSocketSession session, TextMessage message) throws Exception /session.sendMessage(newTextMessage(session.getPrincipal().getName()+",你是第 "+ (sessionMap.size
12、() + "位訪客 "); /p2pObject parse =JSONUtils.parse(message.getPayload();Collection<WebSocketSession> sessions = sessionMap.values();for (WebSocketSession ws : sessions) / 廣播 ws.sendMessage(message);sendMessage(sessionMap.keySet(),"你好 ");Overridepublic voidafterConnecti
13、onEstablished(WebSocketSession session)throws Exception sessionMap.put(session.getPrincipal().getName(),session);super.afterConnectionEstablished(session);Overridepublic voidafterConnectionClosed(WebSocketSession session,CloseStatus status) throws Exception sessionMap.remove(session.getPrincipal().g
14、etName(); super.afterConnectionClosed(session, status);/* 發(fā)送消息* author xiaojf 2017/3/2 11:43*/public static void sendMessage(String username,String message) throws IOException sendMessage(Arrays.asList(username),Arrays.asList(message);/* 發(fā)送消息* author xiaojf 2017/3/2 11:43*/public static voidsendMess
15、age(Collection<String> acceptorList,String message) throws IOException sendMessage(acceptorList,Arrays.asList(message);/* 發(fā)送消息, p2p 群發(fā)都支持* author xiaojf 2017/3/2 11:43*/public static voidsendMessage(Collection<String> acceptorList,Collection<String> msgList)
16、 throws IOException if (acceptorList != null && msgList !=null) for (String acceptor : acceptorList) WebSocketSession session =sessionMap.get(acceptor);if (session != null) for (String msg : msgList) session.sendMessage(newTextMessage(msg.getBytes();前端 js ,需要依賴jqueryrequire("jquery","formUtil", function ($) var url = 'ws:/'+window.location.host+'/web/count' var ws = new WebSocket(url); ws.onopen = function(e)/ ws.send('hello');ws.onmessage = function(e) alert(e.data);ws.onerror = function(e) aler
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 系統(tǒng)分析師考試時(shí)間管理技巧試題及答案
- 綠化苗木買賣合同協(xié)議書
- 質(zhì)量保證與測試的試題及答案
- 檢驗(yàn)生化考試題庫及答案
- 博物館工程管理制度
- 醫(yī)藥原材料管理制度
- 物流員考試題庫及答案
- 如何提升考試分?jǐn)?shù)軟件評(píng)測師試題及答案
- 計(jì)算機(jī)三級(jí)信息管理的學(xué)習(xí)與運(yùn)用試題及答案
- 社會(huì)大講堂管理制度
- 變壓器維修投標(biāo)方案
- 2025屆山東師范大學(xué)附中高考適應(yīng)性考試歷史試卷含解析
- 四川省高職單招餐飲類《中式烹飪技藝》復(fù)習(xí)備考試題庫-下(判斷、簡答題)
- DL∕T 5783-2019 水電水利地下工程地質(zhì)超前預(yù)報(bào)技術(shù)規(guī)程
- SMP-04-022-00 共線生產(chǎn)管理規(guī)程
- 中考字音字形練習(xí)題(含答案)-字音字形專項(xiàng)訓(xùn)練
- 北京市西城區(qū)2023-2024學(xué)年七年級(jí)下學(xué)期期末考試數(shù)學(xué)試卷
- 2024年連云港市名小六年級(jí)畢業(yè)考試語文模擬試卷
- 枯死松樹清理服務(wù)投標(biāo)方案(完整技術(shù)標(biāo))
- 2024年四川省水電投資經(jīng)營集團(tuán)普格電力有限公司招聘筆試參考題庫含答案解析
- 制冷行業(yè)的法律法規(guī)與安全生產(chǎn)標(biāo)準(zhǔn)
評(píng)論
0/150
提交評(píng)論