[websocket]springboot實現websocket

package com.example.demo.websocket;

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

/**
 * 開啓WebSocket支持。
 *
 * @author Da
 * @since 2019.6.18
 */
@Configuration
public class WebSocketConfig {

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

}

package com.example.demo.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;
//import cn.hutool.log.Log;// 使用@Slf4j
//import cn.hutool.log.LogFactory;// 使用@Slf4j
import lombok.extern.slf4j.Slf4j;

/**
 * @see <a>https://blog.csdn.net/moshowgame/article/details/80275084</a>
 * @see <a>http://www.ruanyifeng.com/blog/2017/05/websocket.html</a>
 *
 * 支持的瀏覽器:
 * @see <a>https://caniuse.com/#search=websockets<a/>
 */
@ServerEndpoint("/websocket/{sid}")
@Component
@Slf4j// 增長
public class WebSocketServer {

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

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

    //接收sid
    private String sid = "";

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

    /**
     * 鏈接關閉調用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中刪除
        subOnlineCount();           //在線數減1
        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 static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
        log.info("推送消息到窗口" + sid + ",推送內容:" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //這裏能夠設定只推送給這個sid的,爲null則所有推送
                if (sid == null || "all".equals(sid)) {
                    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--;
    }
}

package com.example.demo.websocket;

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

import java.io.IOException;

@Controller
@RequestMapping("/checkcenter")
public class CheckCenterController {

    /**
     * 推送數據接口。
     *
     * 樣例:
     * 推送單個電視:http://localhost:8080/checkcenter/socket/push/20?message=notice
     * 推送所有電視:http://localhost:8080/checkcenter/socket/push/all?message=notice
     *
     * @param cid 客戶端的id
     * @param message 推送的消息內容
     * @return json字符串,包含客戶端的id與消息內容或異常內容
     */
    @ResponseBody
    @RequestMapping("/socket/push/{cid}")
    public String pushToWeb(@PathVariable String cid, String message) {
        try {
            WebSocketServer.sendInfo(message, cid);
        } catch (IOException e) {
            e.printStackTrace();
            return "{id:" + cid + ", error:" + e.getMessage() + "}";
        }
        return "{id:" + cid + ", message:" + message + "}";
    }
}
<!-- 增長websocket 2019.6.18 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Client</title>
</head>
<body>

<script>
    /**
     * 能夠直接打開本html,無需web服務器。
     */
    var socket;
    if(typeof(WebSocket) == "undefined") {
        console.log("您的瀏覽器不支持WebSocket");
    }else{
        console.log("您的瀏覽器支持WebSocket");
        //實現化WebSocket對象,指定要鏈接的服務器地址與端口  創建鏈接
        // 20表示該客戶端的id,每一個客戶端的id應該不一樣
        socket = new WebSocket("ws://localhost:8080/websocket/20");
        //等同於
        // socket = new WebSocket("http://localhost:8080/checkcenter/websocket/20").replace("http", "ws");
        // socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));

        //打開事件
        socket.onopen = function() {
            console.log("Socket 已打開");
            //socket.send("這是來自客戶端的消息" + location.href + new Date());
        };

        //得到消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            //發現消息進入,開始處理前端觸發邏輯
            if (msg.data == "notice") {
                // 跳轉到公告頁面
                window.location.href = "./notice.html";
            }
        };

        //關閉事件
        socket.onclose = function() {
            console.log("Socket已關閉");
        };

        //發生了錯誤事件
        socket.onerror = function() {
            alert("Socket發生了錯誤");
            //此時能夠嘗試刷新頁面
        }

        //離開頁面時,關閉socket
        //jquery1.8中已經被廢棄,3.0中已經移除
        // $(window).unload(function(){
        //     socket.close();
        //});
    }
</script>
</body>
</html>

socket = new WebSocket("ws://localhost:8080/websocket/22");

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Notice</title>
</head>
<body>
Notice.
</body>
</html>
相關文章
相關標籤/搜索