WebSocket實現方式

js部分:

var websocket = null;
            //判斷瀏覽器是否支持websocket
            if('WebSocket' in window){
                websocket = new WebSocket("ws://localhost:8902/aqfh/WebSocket");
                websocket.onopen = function(){

				}
                websocket.οnerrοr=function(){
                    websocket.send("客戶端連接失敗");
                }
                websocket.onclose=function(){
                    websocket.send("客戶端連接關閉");
                }
                websocket.onmessage=function(e){
                    //收到服務器消息後調用的方法,自己定義
                    send(e.data);
                }
                //監聽異常事件
                window.onbeforeunload = function () {
                    closeWebSocket();
                }
			}else{
                alert("請換個瀏覽器再試!")
			}
需要注意的是,網頁訪問的地址一定要和連接的websocket地址對應上,否則會連接失敗

java部分:

WebServer類,主要是處理和前臺的連接

@Component
@EnableScheduling
@ServerEndpoint("/WebSocket")
public class WebServer {
    //socket連接
    private Session session;

    //建立連接調用的方法
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        WebSocketUtil.add(this);
    }
    //發送消息
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);  //同步方法
    }
    //關閉調用
    @OnClose
    public void onClose(){
        WebSocketUtil.remove(this);
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("來自客戶端的消息:" + message);
    }

    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("發生錯誤");
        error.printStackTrace();
    }
}

WebSocketUtil類,用來管理;連接,以及給前端發送消息

public class WebSocketUtil {
      //用來存儲所有連接
    private static List<WebServer> list = Collections.synchronizedList(new ArrayList<WebServer>());

    public static void sendMessage(String message){
        //遍歷當前所有客戶端連接,分別給發送消息
        for(WebServer server:list){
            try {
                server.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //獲取連接數
    public static int getTotal(){
        return list.size();
    }
    //增加連接
    public static void add(WebServer ser){
        list.add(ser);
    }
    //刪除鏈接
    public static void remove(WebServer ser){
        list.remove(ser);
    }
}

最後是一個處理業務的類,查詢相關的業務數據,滿足條件推送給前臺,具體代碼就不貼了,可以是個線程,或者是定時任務

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章