Spring Boot WebSocket

weixin_34393428發表於2018-10-11

1. SpringBoot2對WebSocket的支援很贊

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

2. WebSocketConfig

  package com.springboot.websocket.config;
  import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 importorg.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
    return new ServerEndpointExporter();
  }
  }

3.WebSocketServer

  因為WebSocket是類似客戶端服務端的形式(採用ws協議),那麼這裡 
的WebSocketServer其實就相當於一個ws協議的Controller 
 直接@ServerEndpoint(“/websocket”)@Component啟用即可,然後在 
裡面實現@OnOpen,@onClose,@onMessage等方法 
package com.springboot.websocket.config;
 import java.io.IOException;
 import java.util.concurrent.CopyOnWriteArraySet;
  import javax.websocket.OnClose;
  import javax.websocket.OnError;
  import javax.websocket.OnMessage;
  import javax.websocket.OnOpen;
   import javax.websocket.Session;
 import javax.websocket.server.PathParam;
  import javax.websocket.server.ServerEndpoint;
  import org.springframework.stereotype.Component;
  @ServerEndpoint("/websocket")
  @Component
  public class WebSocketServer {
//靜態變數,用來記錄當前線上連線數。應該把它設計成執行緒安全的。
private static int onlineCount = 0;
//concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

//與某個客戶端的連線會話,需要通過它來給客戶端傳送資料
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("WebSocket 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 (WebSocketServer 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);
}


/**
 * 群發自定義訊息
 */
public static void sendInfo(String message) throws IOException {
    System.out.println("推送訊息內容:" + message);
    for (WebSocketServer item : webSocketSet) {
        try {
            item.sendMessage(message);
        } catch (IOException e) {
            continue;
        }
    }
}

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

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

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

}

4.WebSocketController

  package com.springboot.websocket.controller;
  import com.springboot.websocket.config.WebSocketServer;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
  public class WebSocketController {
//推送資料介面    @RequestMapping("/socket/push")
public String pushMsg(String message) {
    try {
        WebSocketServer.sendInfo(message);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "success";
}
}

5.index.html

  <!DOCTYPE html>
  <html lang="en">
  <head>
<meta charset="UTF-8">
<title>WebSocket</title>
  </head>
<body>
<h2>WebSocket</h2>
  <script>
var socket;
if (typeof(WebSocket) == "undefined") {
    console.log("您的瀏覽器不支援WebSocket");
} else {
    console.log("您的瀏覽器支援WebSocket");
    //實現化WebSocket物件,指定要連線的伺服器地址與埠建立連線
    socket = new WebSocket("ws://localhost:8080/websocket");

    //開啟事件
    socket.onopen = function () {
        console.log("Socket已開啟");
        socket.send("這是來自客戶端的訊息:" + new Date());
    };

    //獲得訊息事件
    socket.onmessage = function (msg) {
        console.log(msg);
        alert(msg);
    };

    //關閉事件
    socket.onclose = function () {
        console.log("Socket已關閉");
    };

    //發生了錯誤事件
    socket.onerror = function () {
        alert("Socket發生了錯誤");
    }
}
</script>
</body>
</html>

6. 執行截圖

13958911-06278d0d10aa5ba7.png!thumbnail
image

相關文章