1. 程式人生 > >訊息推送springboot+websocket簡單demo

訊息推送springboot+websocket簡單demo

這裡為了方便,使用springboot實現。模板引擎使用thymeleaf(預設)。

springboot+websocket demo下載:https://gitee.com/chen_jia_hao/websocket

1、Intellj Idea 建立新的springboot專案。

可參考下面部分截圖:

整個demo結構如下所示:

2、配置類,需配置如下,方可使用websocket。

package com.cjh.websocket.config;

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

/**
 * @author chen jia hao
 */
@Configuration
public class WebConfig {
    /**
     * 支援websocket
     * 如果不使用內建tomcat,則無需配置
     * @return
     */
    @Bean
    public ServerEndpointExporter createServerEndExporter(){
        return new ServerEndpointExporter();
    }
}

3、websocket服務端處理類(核心)

package com.cjh.websocket.controller;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket服務端
 * @author chen jia hao
 */
@Component
@ServerEndpoint(value = "/myWebSocket")
public class MyWebSocket {

    //用來存放每個客戶端對應的MyWebSocket物件
    private static CopyOnWriteArraySet<MyWebSocket> user = new CopyOnWriteArraySet<MyWebSocket>();

    //與某個客戶端的連線會話,需要通過它來給客戶端傳送資料
    private Session session;

    @OnMessage
    public void onMessage(String message,Session session) throws IOException {

        //群發訊息
        for (MyWebSocket myWebSocket : user) {
            myWebSocket.session.getBasicRemote().sendText(session.getId()+"說:"+message);
            //myWebSocket.session.getBasicRemote().sendText("<img src=''/>");
        }
    }

    @OnOpen
    public void onOpen(Session session){
        System.out.println(session.getId()+" open...");
        this.session = session;
        user.add(this);
    }
    @OnClose
    public void onClose(){
        System.out.println(this.session.getId()+" close...");
        user.remove(this);
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println(this.session.getId()+" error...");
        error.printStackTrace();
    }

}

4、前臺介面,聊天測試

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試</title>
    <style>
        #message{
            height: 520px;
            border-bottom: 1px solid gray;
            padding: 20px 30px;
        }
        #container{
            margin: 0 auto;
            width: 720px;
            border: 1px solid gray
        }
        input{
            width: 300px;
            height: 36px;
            border: 1px solid gray;
            background:none;
            outline:none;
        }
        input:focus{
            border-color: yellow;
        }
        button{
            height: 36px;
        }
    </style>
</head>
<body>
<div id="container">
    <div id="message">

    </div>
    <div>
        <input id="text" type="text" placeholder="輸入內容..."/>
        <button onclick="send()">傳送訊息</button>
    </div>
</div>
<script th:inline="javascript" type="text/javascript">
    var websocket = null;

    //判斷當前瀏覽器是否支援WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/myWebSocket");
    }
    else {
        alert('當前瀏覽器不支援websocket');
    }

    //傳送訊息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
    //接收到訊息的回撥方法
    websocket.onmessage = function (event) {
        var data = event.data;
        document.getElementById('message').innerHTML += data+'<br/>';
    }

    //連線成功建立的回撥方法
    websocket.onopen = function () {
        console.log("onopen...");
    }
    //連線關閉的回撥方法
    websocket.onclose = function () {
        console.log("onclose...");
    }
    //連線發生錯誤的回撥方法
    websocket.onerror = function () {
        console.log("onerror...");
    };
    //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }
    //關閉WebSocket連線
    function closeWebSocket() {
        websocket.close();
    }

</script>
</body>
</html>

6、demo效果圖: