SpringBoot 快速實現WebSocket
1.添加Maven依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
2.webSocket配置
/**
* webSocket配置
* @author 陳梓平
* @date 2017/10/25.
*/
@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 這個bean會自動註冊使用了@ServerEndpoint註解聲明的Websocket endpoint
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.自定義websocket
/**
* 自定義websocket
* @author 陳梓平
* @date 2017/10/25.
*/
@ServerEndpoint(value = "/websocket")
@Component
public class CustomWebSocket {
/**靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。*/
private static int onlineCount = 0;
/**concurrent包的線程安全Set,用來存放每個客戶端對應的CumWebSocket對象。*/
private static CopyOnWriteArraySet<CustomWebSocket> webSocketSet = new CopyOnWriteArraySet<CustomWebSocket>();
/**與某個客戶端的連接會話,需要通過它來給客戶端發送數據*/
private Session session;
private static final Logger log = LoggerFactory.getLogger(CustomWebSocket.class);
/**
* 連接建立成功調用的方法
* @param session
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
addOnlineCount();
log.info("新連接接入。當前在線人數爲:"+getOnlineCount());
try {
sendMessage("假裝有內容");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
subOnlineCount();
log.info("有連接關閉。當前在線人數爲:"+getOnlineCount());
}
/**
* 收到客戶端消息後調用
* @param message
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("客戶端發送的消息:"+message);
sendAll(message);
}
/**
* 暴露給外部的羣發
* @param message
* @throws IOException
*/
public static void sendInfo(String message) throws IOException {
sendAll(message);
}
/**
* 羣發
* @param message
*/
private static void sendAll(String message) {
Arrays.asList(webSocketSet.toArray()).forEach(item -> {
CustomWebSocket customWebSocket = (CustomWebSocket) item;
try {
customWebSocket.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
});
}
/**
* 發生錯誤時調用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.info("有異常啦");
error.printStackTrace();
}
/**
* 減少在線人數
*/
private void subOnlineCount() {
CustomWebSocket.onlineCount--;
}
/**
* 添加在線人數
*/
private void addOnlineCount() {
CustomWebSocket.onlineCount++;
}
/**
* 當前在線人數
* @return
*/
public static synchronized int getOnlineCount() {
return onlineCount;
}
/**
* 發送信息
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
}
4.前端頁面
<!DOCTYPE HTML>
<html>
<head>
<title>WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/websocket");
}
else{
alert('Not support websocket')
}
websocket.onerror = function(){
setMessageInnerHTML("error");
};
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
websocket.onclose = function(){
setMessageInnerHTML("close");
}
window.onbeforeunload = function(){
websocket.close();
}
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
function closeWebSocket(){
websocket.close();
}
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
5.測試