springboot集成websocket實現向前端瀏覽器發送一個對象,發送消息操做手動觸發

工做中有這樣一個需示,咱們把項目中用到代碼緩存到前端瀏覽器IndexedDB裏面,當系統管理員在後臺對代碼進行變更操做時咱們要更新前端緩存中的代碼怎麼作開始用想用版本方式來處理,但這樣的話每次使用代碼以前都須要調用獲取版本API來判斷版本是否有變化來是否更新本地代碼,這樣的話對服務器形成很大的壓力。後來考慮http慢輪訊方式,最後瞭解到WebSocket這簡直是神器,之後還可用來擴展項目中的即時聊天功能。javascript

WebSocket是什麼

咱們知道HTTP協議都是先由瀏覽器向服務器發送請求,服務器響應這個請求,再把數據發送給瀏覽器。 若是須要服務器發送消息給瀏覽器怎麼辦 WebSocket是HTML5新增的協議,讓瀏覽器和服務器之間能夠創建無限制的全雙工通訊,任何一方均可以主動發消息給對方。html

SpringBoot-Websocket-Demo

項目介紹

  • springboot 2.1.6.RELEASE前端

  • spring-boot-starter-websocketjava

  • 本項目主要爲了測試springboot集成websocket實現向前端瀏覽器發送一個對象,發送消息操做手動觸發。git

代碼已上傳到github 傳送門 https://github.com/devmuyuer/SpringBoot-Websocket-Demogithub

代碼說明

  • 1.新建spingboot項目web

  • 2.加入WebSocket依賴
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • 3.WebSocketConfig
    開啓WebSocket支持
package com.example.socket;

/**
 * @author muyuer 182443947@qq.com
 * @version 1.0
 * @date 2019-07-22 18:16
 */

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * 開啓WebSocket支持
 * @author zhengkai
 */
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}
  • 4.WebSocketServer
    WebSocket採用ws協議,這裏的WebSocketServer相似於一個ws協議的Controller
package com.example.socket;

import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * @author muyuer 182443947@qq.com
 * @version 1.0
 * @date 2019-07-22 18:17
 */
@ServerEndpoint("/web/socket/{sid}")
@Component
public class WebSocketServer {

    static Log log=LogFactory.get(WebSocketServer.class);
    /**
     * 靜態變量,用來記錄當前在線鏈接數。應該把它設計成線程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    /**
     * 與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據
     */
    private Session session;

    /**
     * 接收sid
      */
    private String sid="";
    /**
     * 鏈接創建成功調用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        //在線數加1
        addOnlineCount();
        log.info("有新窗口開始監聽:"+sid+",當前在線人數爲" + getOnlineCount());
        this.sid=sid;
        try {
            sendMessage("鏈接成功");
        } catch (IOException e) {
            log.error("websocket IO異常");
        }
    }

    /**
     * 鏈接關閉調用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("有一鏈接關閉!當前在線人數爲" + getOnlineCount());
    }

    /**
     * 收到客戶端消息後調用的方法
     *
     * @param message 客戶端發送過來的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到來自窗口"+sid+"的信息:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("發生錯誤");
        error.printStackTrace();
    }
    /**
     * 實現服務器主動推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    /**
     * 實現服務器主動推送
     */
    public void sendMessage(SocketMessage message) throws IOException {
        this.session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));
    }


    /**
     * 羣發自定義消息
     * */
    public static void sendInfo(SocketMessage message,@PathParam("sid") String sid) throws IOException {
        log.info("推送消息到窗口"+sid+",推送內容:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                if(sid==null) {
                    item.sendMessage(message);
                }else if(item.sid.equals(sid)){
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
  • 5.WebSocketController
    測試用api 可在項目中調用 WebSocketServer.sendInfo(newMessage,cid);推送消息
package com.example.socket;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Date;

/**
 * @author muyuer 182443947@qq.com
 * @version 1.0
 * @date 2019-07-22 18:19
 */
@Controller
@RequestMapping("/web/socket")
public class WebSocketController {

    /**
     * 頁面請求
     * @param cid
     * @return
     */
    @GetMapping("/{cid}")
    public ModelAndView socket(@PathVariable String cid) {
        ModelAndView mav=new ModelAndView("/socket");
        mav.addObject("cid", cid);
        return mav;
    }

    /**
     * 推送數據接口
     * @param cid
     * @param message
     * @return
     */
    @ResponseBody
    @RequestMapping("/send/")
    public String pushToWeb(String cid,String message) {
        try {
            SocketMessage newMessage = new SocketMessage(message, new Date());
            WebSocketServer.sendInfo(newMessage,cid);
        } catch (IOException e) {
            e.printStackTrace();
            return cid+"#"+e.getMessage();
        }
        return cid;
    }
}

-6. 前端調用代碼spring

<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判斷當前瀏覽器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8083/web/socket/20");
    }
    else{
        alert('Not support websocket')
    }

    //鏈接發生錯誤的回調方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //鏈接成功創建的回調方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }

    //接收到消息的回調方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }

    //鏈接關閉的回調方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

    //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket鏈接,防止鏈接還沒斷開就關閉窗口,server端會拋異常。
    window.onbeforeunload = function(){
        websocket.close();
    }

    //將消息顯示在網頁上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //關閉鏈接
    function closeWebSocket(){
        websocket.close();
    }

    //發送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

測試

  • 1.f9運行項目,項目端口是8083能夠配置文件中修改
  • 2.首先在瀏覽器中打開地址 http://localhost:8083/ 創建鏈接
  • 3.訪問地址 http://localhost:8083/web/socket/send?cid=20&message=hello 推送消息 cid是客戶端創建鏈接id 也就是html中"ws://localhost:8083/web/socket/20"的id 20

參考資料

相關文章
相關標籤/搜索