SpringBoot WebSocket 實例

事務(Transaction)總結

1. 首先建立一個SpringBoot項目,指定端口號爲10000(可自由設置)

2. 在pom.xml文件裏引入websocket包

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

3. 建立WebSocketConfig配置文件

@Configuration
public class WebSocketConfig {
    [@Bean](https://my.oschina.net/bean)
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

4. 建立WebSocketServer類

@ServerEndpoint("/websocket")
[@Component](https://my.oschina.net/u/3907912)
[@Slf4j](https://my.oschina.net/slf4j)
@Scope("prototype")
public class WebSocketServer {

    //靜態變量,用來記錄當前在線鏈接數
    private static final AtomicInteger onlineCount = new AtomicInteger(0);
    //concurrent包的線程安全Set,用來存放每一個客戶端對應的MyWebSocket對象。
    private static CopyOnWriteArraySet<Session> sessionSet = new CopyOnWriteArraySet<>();

    public static void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)", message, session.getId()));
        } catch (IOException e) {
            log.error("發送消息出錯:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 羣發消息
     */
    public static void BroadCastInfo(String message) throws IOException {
        for (Session session : sessionSet) {
            if (session.isOpen()) {
                sendMessage(session, "收到消息,消息內容:" + message);
            }
        }
    }

    /**
     * 指定Session發送消息
     *
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void SendMessage(String sessionId, String message) throws IOException {
        Session session = null;
        for (Session s : sessionSet) {
            if (s.getId().equals(sessionId)) {
                session = s;
                break;
            }
        }
        if (session != null) {
            sendMessage(session, message);
        } else {
            log.warn("沒有找到你指定ID的會話:{}", sessionId);
        }
    }

    /**
     * 鏈接成功 調用
     */
    @OnOpen
    public void onOpen(Session session) {
        sessionSet.add(session);
        log.info("有新窗口開始監聽,當前在線人數爲" + onlineCount.incrementAndGet());

    }

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

    /**
     * 接客戶端消息
     *
     * @param message 客戶端發送消息
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("收到來自窗口的信息:" + message);
        BroadCastInfo("收到消息,消息內容:" + message);

    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("發生錯誤:{},Session ID: {}", error.getMessage(), session.getId());
        error.printStackTrace();
    }

}

5. 建立restful接口,用於服務端手工推送任務

@RestController
@RequestMapping("/api/ws")
public class WebSocketController {

    /**
     * 羣發消息內容
     *
     * @param message
     * @return
     */
    @RequestMapping(value = "/sendAll", method = RequestMethod.GET)
    public String sendAllMessage(@RequestParam String message) {
        try {
            WebSocketServer.BroadCastInfo(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    /**
     * 指定會話ID發消息
     *
     * @param message 消息內容
     * @param id      鏈接會話ID
     * @return
     */
    @RequestMapping(value = "/sendOne", method = RequestMethod.GET)
    public String sendOneMessage(@RequestParam String message,
                                 @RequestParam String id) {
        try {
            WebSocketServer.SendMessage(id, message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }
}

6. 建立前端測試頁面

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>websocket測試</title>
    <style type="text/css">
        h3,h4{
            text-align:center;
        }
    </style>
</head>
<body>

<h3>WebSocket測試,在<span style="color:red">控制檯</span>查看測試信息輸出!</h3>
<h4>http://wallimn.iteye.com</h4>
<h4>
    [url=/api/ws/sendOne?message=單發消息內容&id=none]單發消息連接[/url]
    [url=/api/ws/sendAll?message=羣發消息內容]羣發消息連接[/url]
</h4>
<div id="msgDiv" style="width: 400px;height: 300px;background-color: bisque;"></div>
<textarea id="msgTxt"></textarea>
<input type="button" onclick="sendMsg()" value="發送">


<script type="text/javascript">
    var socket;
    if (typeof (WebSocket) == "undefined") {
        console.log("遺憾:您的瀏覽器不支持WebSocket");
    } else {
        console.log("恭喜:您的瀏覽器支持WebSocket");

        //實現化WebSocket對象
        //指定要鏈接的服務器地址與端口創建鏈接
        //注意ws、wss使用不一樣的端口。我使用自簽名的證書測試,
        //沒法使用wss,瀏覽器打開WebSocket時報錯
        //ws對應http、wss對應https。
        socket = new WebSocket("ws://localhost:10000/websocket");
        //鏈接打開事件
        socket.onopen = function() {
            console.log("Socket 已打開");
            socket.send("消息發送測試(From Client)");
        };
        //收到消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            document.getElementById("msgDiv").append("<p>"+msg.data+"</p>");
        };
        //鏈接關閉事件
        socket.onclose = function() {
            console.log("Socket已關閉");
        };
        //發生了錯誤事件
        socket.onerror = function() {
            alert("Socket發生了錯誤");
        }

        //窗口關閉時,關閉鏈接
        window.unload=function() {
            socket.close();
        };
    }
    function sendMsg(){
        var msg=document.getElementById("msgTxt").value;
        socket.url
        socket.send(msg);
    }
</script>

</body>
</html>
相關文章
相關標籤/搜索