websocket的簡單使用

1、maven專案,第一步需要配置jar包

org。springframework。boot

spring-boot-starter-websocket

2、前臺使用

var websocket = null;

//判斷當前瀏覽器是否支援WebSocket

if(‘WebSocket’ in window){

//連線WebSocket節點

websocket = new WebSocket(“ws://localhost:81/api/imserver/”+使用者id;);

}else{

console。log(“您的瀏覽器不支援WebSocket”);

}

//連線發生錯誤的回撥方法

websocket。onerror = function(){

};

//連線成功建立的回撥方法

websocket。onopen = function(event){

}

//接收到訊息的回撥方法

websocket。onmessage = function(event){

setMessageInnerHTML(event。data);

}

//連線關閉的回撥方法

websocket。onclose = function(){

}

//傳送訊息

function send(){

var message = document。getElementById(‘text’)。value;

websocket。send(message);

}

視窗關閉或者退出登入時呼叫,如果掛掉需要重新請求

//監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。

window。onbeforeunload = function(){

websocket。close();

}

前臺檢測後臺是否掛掉

//針對斷網的情況的心跳重連

var heartCheck = {

timeout: 20000,//20ms

timeoutObj: null,

reset: function( ){

clearTimeout(this。timeoutObj);

this。start();

},

start: function( ){

this。timeoutObj = setTimeout(function(){

websocket。send(“HeartBeat”); //自定義需要執行的命令

}, this。timeout)

}

};

heartCheck。start();

heartCheck。reset();

//將訊息顯示在網頁上

function setMessageInnerHTML(innerHTML){

document。getElementById(‘message’)。innerHTML += innerHTML + ‘
’;

}

3、後臺使用

新建WebSocketConfig 類

@Configuration

public class WebSocketConfig {

@Bean

public ServerEndpointExporter serverEndpointExporter() {

return new ServerEndpointExporter();

}

}

新建WebSocketServer類

@ServerEndpoint(value=“/imserver/{userId}”)

@Component

public class WebSocketServer {

private final static Logger log = LoggerFactory。getLogger(WebSocketServer。class);

/**靜態變數,用來記錄當前線上連線數。應該把它設計成執行緒安全的。*/

private static int onlineCount = 0;

/**concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。*/

private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();

/**與某個客戶端的連線會話,需要透過它來給客戶端傳送資料*/

private Session session;

/**接收userId*/

private String userId=“”;

/**

* 連線建立成功呼叫的方法

**/

@OnOpen

public void onOpen(Session session,@PathParam(“userId”) String userId) {

this。session = session;

this。userId=userId;

if(webSocketMap。containsKey(userId)){

webSocketMap。remove(userId);

webSocketMap。put(userId,this);

//加入set中

}else{

webSocketMap。put(userId,this);

//加入set中

addOnlineCount();

//線上數加1

}

log。info(“使用者連線:”+userId+“,當前線上人數為:” + getOnlineCount());

try {

sendMessage(“”);

} catch (IOException e) {

log。error(“使用者:”+userId+“,網路異常!!!!!!”);

}

}

/**

* 連線關閉呼叫的方法

*/

@OnClose

public void onClose() {

if(webSocketMap。containsKey(userId)){

webSocketMap。remove(userId);

//從set中刪除

subOnlineCount();

}

log。info(“使用者退出:”+userId+“,當前線上人數為:” + getOnlineCount());

}

/**

* 收到客戶端訊息後呼叫的方法

*

* @param message 客戶端傳送過來的訊息*/

@OnMessage

public void onMessage(String message, Session session) {

//log。info(“使用者訊息:”+userId+“,報文:”+message);

//可以群發訊息

//訊息儲存到資料庫、redis

if(StringUtils。isNotBlank(message)){

try {

if(“ping”。equals(message)) {

webSocketMap。get(userId)。sendMessage(“pong”);

}else {

//解析傳送的報文

JSONObject jsonObject = JSON。parseObject(message);

//追加發送人(防止串改)

jsonObject。put(“fromUserId”,this。userId);

String toUserId=jsonObject。getString(“toUserId”);

//傳送給對應toUserId使用者的websocket

if(StringUtils。isNotBlank(toUserId)&&webSocketMap。containsKey(toUserId)){

webSocketMap。get(toUserId)。sendMessage(jsonObject。toJSONString());

}else{

log。error(“請求的userId:”+toUserId+“不在該伺服器上”);

//否則不在這個伺服器上,傳送到mysql或者redis

}

}

}catch (Exception e){

e。printStackTrace();

}

}

}

/**

* 使用者錯誤

* @param session

* @param error

*/

@OnError

public void onError(Session session, Throwable error) {

log。error(“使用者錯誤:”+this。userId+“,原因:”+error。getMessage());

}

/**

* 實現伺服器主動推送

*/

public void sendMessage(String message) throws IOException {

this。session。getBasicRemote()。sendText(message);

}

/**

* 傳送自定義訊息

* */

public static void sendInfo(String message,@PathParam(“userId”) String userId) {

try {

log。info(“傳送訊息到:”+userId+“,報文:”+message);

if(StringUtils。isNotBlank(userId)&&webSocketMap。containsKey(userId)){

webSocketMap。get(userId)。sendMessage(message);

}else{

log。error(“使用者”+userId+“,不線上!”);

}

} catch (Exception e) {

log。error(“異常”+userId+“,報文:”+message);

}

}

public static synchronized int getOnlineCount() {

return onlineCount;

}

public static synchronized void addOnlineCount() {

WebSocketServer。onlineCount++;

}

public static synchronized void subOnlineCount() {

WebSocketServer。onlineCount——;

}

}

後臺使用時呼叫其傳送方法,前臺就可以收到,然後修改頁面顯示

WebSocketServer。sendInfo(“”,userid);

謝謝觀看!!!

websocket的簡單使用