為什麼要要用websocket呢?websocket相對於傳統http協議有什麼優勢呢?
websocket響應報文
好了,簡單的了解一下,我們來看看springboot+websocket實現推送的過程,以下是個簡單的demo。
websocket依賴
@Componentpublic class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
@Component@ServerEndpoint(value = &34;)public class LoggingWSServer { private static final Logger LOGGER = LoggerFactory.getLogger(LoggingWSServer.class); private static Map<String, Session> sessionMap = new ConcurrentHashMap<>(); private static Gson gson = new Gson(); private static Map<String,Object> map = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session) { new Thread(() -> { // 這裡大家可以根據業務來優化,使用線程池等手段 while(sessionMap.get(session.getId()) != null) { try { List<AaaServer> list = aaaServerService.findList(); if(session.isOpen()) { send(session, gson.toJson(list)); } Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } @OnClose public void onClose(Session session) { sessionMap.remove(session.getId()); LOGGER.info(&34; , session.getId()); } @OnMessage public void onMessage(String message,Session session) { LOGGER.info(&34;,message); map.put(&34;,message); send(session,gson.toJson(map)); } private void send(Session session, String toJson) { try { session.getBasicRemote().sendText(toJson); } catch (IOException e) { LOGGER.error(&34;,e.getMessage()); } } }
服務端api解釋:
//websocket對象 var websocket = null; //判斷當前瀏覽器是否支持WebSocket if (&39; in window) { //動態獲取域名或ip var hostname = window.location.hostname; port = window.location.port; websocket = new WebSocket(&34;+hostname+&34; + port + &34;); } else { console.error(&34;); } //連接發生錯誤的回調方法 websocket.onerror = function (e) { console.error(&34; + e); }; //連接成功建立的回調方法 websocket.onopen = function () { console.log(&34;) }; //接收到消息的回調方法 websocket.onmessage = function (event) { console.log(&34;, event.data ); var data = JSON.parse(event.data); if (data.push) { // 內容 var temp = template(&39;,{data : data.push}); console.log(&34; + temp); document.getElementById(&34;).innerHTML = temp; } if(data.ret) { console.log(data.ret) alert(data.ret); } } //發送消息 $(&send&39;39;).val()); });
前端頁面注意:
今天就簡單的介紹到這裡,有需要這個demo的,可以關注一下小編,後續小編會把代碼上傳到gitee,https://gitee.com/bigqianqian/springboot-websocket,可以了解下。下篇文章小編將會介紹websocket點對點推送和廣播,喜歡的朋友點個關注唄[奮鬥][奮鬥][奮鬥],也可以動動手評論下,留下你的理解,小編與你共同成長!