首先,用idea搭建一個springboot項目
如此如此就不需要演示了把
接下來pom文件引入websocket依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
然後,配置websocket,把websocket加入IOC容器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
OK,然後咱們繼續寫websocket的服務端
- @ServerEndpoint(value = "/ws/asset")表示websocket的接口服務地址
- @OnOpen註解的方法,爲連接建立成功時調用的方法
- @OnClose註解的方法,爲連接關閉調用的方法
- @OnMessage註解的方法,爲收到客戶端消息後調用的方法
- @OnError註解的方法,爲出現異常時調用的方法
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
/**
* WebSocket服務端示例
*/
@Component
@Slf4j
@ServerEndpoint(value = "/ws/asset")
public class WebSocketServer {
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
// concurrent包的線程安全Set,用來存放每個客戶端對應的Session對象。
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<>();
/**
* 連接建立成功調用的方法
*/
@OnOpen
public void onOpen(Session session) throws IOException {
SessionSet.add(session);
int cnt = OnlineCount.incrementAndGet(); // 在線數加1
log.info("有連接加入,當前連接數爲:{}", cnt);
SendMessage(session, "連接成功");
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose(Session session) {
SessionSet.remove(session);
int cnt = OnlineCount.decrementAndGet();
log.info("有連接關閉,當前連接數爲:{}", cnt);
}
/**
* 收到客戶端消息後調用的方法
*
* @param message 客戶端發送過來的消息
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
log.info("來自客戶端的消息:{}", message);
SendMessage(session, "收到消息,消息內容:" + message);
}
/**
* 出現錯誤
*/
public void onError(Session session, Throwable error) {
log.error("發生錯誤:{},Session ID: {}", error.getMessage(), session.getId());
}
/**
* 發送消息,實踐表明,每次瀏覽器刷新,session會發生變化。
*
* @param session session
* @param message 消息
*/
private static void SendMessage(Session session, String message) throws IOException {
session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)", message, session.getId()));
}
/**
* 羣發消息
*
* @param message 消息
*/
public static void BroadCastInfo(String message) throws IOException {
for (Session session : SessionSet) {
if (session.isOpen()) {
SendMessage(session, message);
}
}
}
/**
* 指定Session發送消息
*
* @param sessionId sessionId
* @param message 消息
*/
public static void SendMessage(String sessionId, String message) throws IOException {
Session session = null;
for (Session s : SessionSet) {
if (s.getId().equals(sessionId)) {
session = s;
break;
}
}
if (session != null) {
SendMessage(session, message);
} else {
log.warn("沒有找到你指定ID的會話:{}", sessionId);
}
}
}
服務端有了,那就還差前端了
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>websocket測試</title>
<style type="text/css">
h3,h4{
text-align:center;
}
</style>
</head>
<body>
<h3>WebSocket測試,在<span style="color:red">控制檯</span>查看測試信息輸出!</h3>
<h4>
<br>
http://localhost:8080/api/ws/sendOne?message=單發消息內容&id=none
<br>
http://localhost:8080/api/ws/sendAll?message=羣發消息內容
</h4>
<h3>請輸入要發送給服務器端的消息:</h3><br/>
<input id="text" type="text" />
<button οnclick="sendToServer()">發送服務器消息</button>
<button οnclick="closeWebSocket()">關閉連接</button>
<br>信息:<span id="message"></span>
<script type="text/javascript">
let socket;
if (typeof (WebSocket) == "undefined") {
console.log("遺憾:您的瀏覽器不支持WebSocket");
} else {
socket = new WebSocket("ws://localhost:8080/ws/asset");
//連接打開事件
socket.onopen = function() {
console.log("Socket 已打開");
socket.send("消息發送測試(From Client)");
};
//收到消息事件
socket.onmessage = function(msg) {
document.getElementById('message').innerHTML += msg.data + '<br/>';
};
//連接關閉事件
socket.onclose = function() {
console.log("Socket已關閉");
};
//發生了錯誤事件
socket.onerror = function() {
alert("Socket發生了錯誤");
}
//窗口關閉時,關閉連接
window.unload=function() {
socket.close();
};
}
//關閉連接
function closeWebSocket(){
socket.close();
}
//發送消息給服務器
function sendToServer(){
let message = document.getElementById('text').value;
socket.send(message);
}
</script>
</body>
</html>
點擊run,跑一下把
當有一個客戶端連接上,終端顯示
繼續
點擊發送消息
點擊關閉連接就會出現
OK,測試完畢
記得點個贊、留個關注啊親