if("WebSocket" in window) {
var ws = new WebSocket("ws://127.0.0.1:8090/api/webSocket");
ws.onopen = function() {
ws.send("前端向后台发送的数据...");
}
ws.onmessage = function(evt) {
}
ws.onclose = function() {
}
} else {
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/api/webSocket")
@Component
@Slf4j
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSockets.add(this);
log.info("【新建连接】,连接总数:{}", webSockets.size());
}
@OnClose
public void onClose() {
webSockets.remove(this);
log.info("【断开连接】,连接总数:{}", webSockets.size());
}
@OnMessage
public void onMessage(String message) {
log.info("【收到】,客户端的信息:{},连接总数:{}", message, webSockets.size());
}
public void sendMessage(String message) {
log.info("【广播发送】,信息:{},总连接数:{}", message, webSockets.size());
for (WebSocket webSocket : webSockets) {
try {
webSocket.session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.info("【广播发送】,信息异常:{}", e.fillInStackTrace());
}
}
}
}