springboot簡單使用websocket

添加@Configuration

package com.xsj.xsj1800wsq.config;

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

/**
 * @ClassName WebSocketConfig
 * @Author zx
 * @Date 2019/3/19 16:13
 **/
@Configuration
public class WebSocketConfig {

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

引入websocket包

<!-- message -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

websocket工具類

網上找的一個

package com.xsj.xsj1800wsq.message;

import org.springframework.stereotype.Component;

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

/**
 * @ClassName MyWebSocket
 * @Author zx
 * @Date 2019/3/19 16:15
 **/
@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
    //靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
    private static int onlineCount = 0;

    //concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

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

    /**
     * 連接建立成功調用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在線數加1
        System.out.println("有新連接加入!當前在線人數爲" + getOnlineCount());
        try {
            sendMessage("歡迎");
        } catch (IOException e) {
            System.out.println("IO異常");
        }
    }

    /**
     * 連接關閉調用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中刪除
        subOnlineCount();           //在線數減1
        System.out.println("有一連接關閉!當前在線人數爲" + getOnlineCount());
    }

    /**
     * 收到客戶端消息後調用的方法
     *
     * @param message 客戶端發送過來的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("來自客戶端的消息:" + message);

        //羣發消息
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


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

     public void sendMessage(String message) throws IOException {
     this.session.getBasicRemote().sendText(message);
     //this.session.getAsyncRemote().sendText(message);
     }



     /**
      * 羣發自定義消息
      * */
    public static void sendInfo(String message) throws IOException {
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

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

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

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}

js前端調用

鏈接url:ws://IP:PORT/PROJECT_NAME/websocket
改爲自己的IP端口,項目名

if('WebSocket' in window) {
	console.log("此瀏覽器支持websocket");
	websocket = new WebSocket("ws://IP:PORT/PROJECT_NAME/websocket");
} else if('MozWebSocket' in window) {
	alert("此瀏覽器只支持MozWebSocket");
} else {
	alert("此瀏覽器只支持SockJS");
}
websocket.onopen = function(event) {
	console.log("鏈接服務器成功!");
};
websocket.onmessage = function(event) {
	//打印接受的數據
	alert(event.data);
};
websocket.onerror = function(event) {};
websocket.onclose = function(event) {
	alert("與服務器斷開了鏈接!");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章