pom引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocketConfigo配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @description:
* @author: xumiaofeng
* @date: 2019/3/28 0028 13:58
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocket
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocket {
//靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
//concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
//與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
/**
* 羣發自定義消息
*/
public static void sendInfo(String message) throws IOException {
for (WebSocket item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
/**
* 連接建立成功調用的方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數加1
System.out.println("webSocket有新連接加入!當前在線人數爲" + getOnlineCount());
}
/**
* 連接關閉調用的方法
*/
@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);
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
long initialDelay = 1;
long period = 5;
// 從現在開始1秒鐘之後,每隔1秒鐘執行一次job1
service.scheduleAtFixedRate(() -> {
JSONArray jsonArray = JSON.parseArray(message);
jsonArray.stream().map(object -> (JSONObject) object).forEach(jsonObject -> {
String id = jsonObject.getString("id");
jsonObject.put("value", (int) (1 + Math.random() * (100)));
});
String jsonString = jsonArray.toString();
//羣發消息
for (WebSocket item : webSocketSet) {
try {
item.sendMessage(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
}, initialDelay, period, TimeUnit.SECONDS);
}
@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);
}
}
websocket測試頁面
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text"/>
<button "send()">Send</button>
<button "closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判斷當前瀏覽器是否支持WebSocket
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");
}
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
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>
SVG頁面實現自動刷新
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function () {
// 初始化內容
var message = [];
$(".attr").each(function () {
this.textContent = 0;
message.push({
"id": this.id
})
})
var message = JSON.stringify(message)
if (websocket.readyState !== 1) {
//等待1s,webSocket狀態變爲open,才能發送消息
setTimeout(function () {
send(message);
}, 1000);
} else {
send(message);
}
});
</script>
<script type="text/javascript">
var websocket = null;
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/websocket");
} else {
alert('Not support websocket')
}
//連接發生錯誤的回調方法
websocket.onerror = function () {
console.log("error")
};
//連接成功建立的回調方法
websocket.onopen = function (event) {
console.log("open")
}
//接收到消息的回調方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//連接關閉的回調方法
websocket.onclose = function () {
console.log("close")
}
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function () {
websocket.close();
}
//將消息顯示在網頁上
function setMessageInnerHTML(innerHTML) {
console.log(innerHTML);
var message = eval('(' + innerHTML + ')');
for (var index in message) {
document.getElementById(message[index].id).textContent = message[index].value;
}
// document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//開啓鏈接
function openWebSocket() {
websocket.open();
}
//關閉連接
function closeWebSocket() {
websocket.close();
}
//發送消息
function send(message) {
websocket.send(message);
}
</script>
<body>
<svg height="500" version="1.1" width="700" xmlns="http://www.w3.org/2000/svg">
<g>
<rect fill="#FFFFFF" height="100" stroke="#000000"
transform="matrix(1,0,0,1,13,62) matrix(1,0,0,1,39,17) matrix(1,0,0,1,86,9)" width="100" x="110"
xmlns="http://www.w3.org/2000/svg"
y="119"/>
<line stroke="#000000" transform="matrix(1,0,0,1,13,62) matrix(1,0,0,1,39,17) matrix(1,0,0,1,86,9)" x1="110"
x2="209" xmlns="http://www.w3.org/2000/svg"
y1="219"
y2="120"/>
<text fill="#000000" font-family="Microsoft YaHei UI" font-size="15" stroke="#000000" stroke-dasharray="10,10"
stroke-width="0.25"
transform="matrix(1,0,0,1,13,62) matrix(1,0,0,1,39,17)" x="215" xml:space="preserve"
xmlns="http://www.w3.org/2000/svg" y="159">
AC</text>
<text baseline-shift="baseline" fill="#000000" font-family="Microsoft YaHei UI" font-size="15" stroke="#000000"
transform="matrix(1,0,0,1,13,62) "
x="298" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"
y="215">
DC</text>
<line stroke="#000000" x1="300" x2="300" xmlns="http://www.w3.org/2000/svg" y1="208" y2="110"/>
<line stroke="#000000" x1="300" x2="300" xmlns="http://www.w3.org/2000/svg" y1="308" y2="396"/>
<text baseline-shift="baseline" fill="#000000" font-family="Microsoft YaHei UI" font-size="15" stroke="#000000"
x="314"
xml:space="preserve" xmlns="http://www.w3.org/2000/svg" y="128">
</text>
<text class="attr" fill="#000000" font-family="Microsoft YaHei UI" font-size="12" id="acPower" stroke="#000000"
x="337"
xml:space="preserve" xmlns="http://www.w3.org/2000/svg" y="147">
###</text>
<text class="attr" fill="#000000" font-family="Microsoft YaHei UI" font-size="12" id="dcPower" stroke="#000000"
x="337"
xml:space="preserve" xmlns="http://www.w3.org/2000/svg" y="347">
###</text>
</g>
</svg>
</body>
</html>
坑
- 如項目有shiro框架,需要登錄後,webSocket才能發送數據。因爲只有登錄ws鏈接才能通;
- 頁面初始刷新webSocket會報錯,再次刷新就正常了,原因是初始化出webSocket還未到open狀態,需等待1s中,再發生數據