1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2 添加socket配置类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3 添加WebSocketServer类
@ServerEndpoint("/websocket/info/{stationId}")
@Component
@Slf4j
public class WebSocketServer {
private volatile static int onlineCount = 0;
public volatile static Map<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
private Session session;
private String stationId;
public static void sendInfo(Long id, String msg) {
WebSocketServer wb = webSocketMap.get(String.valueOf(id.longValue()));
if (wb != null) {
try {
wb.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@OnOpen
public void onOpen(@PathParam("stationId") String stationId, Session session){
this.session = session;
this.stationId = stationId;
webSocketMap.put(this.stationId, this);
addOnlineCount();
log.info("有新连接加入!当前在线连接为" + getOnlineCount());
}
@OnClose
public void onClose(){
webSocketMap.remove(this.stationId);
subOnlineCount();
log.info("有一连接关闭!当前在线连接为" + getOnlineCount());
}
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:" + message);
for (Map.Entry<String, WebSocketServer> entry : webSocketMap.entrySet()) {
try {
entry.getValue().sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
@OnError
public void onError(Session session, Throwable error){
log.info("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
4 添加客户端页面
<!DOCTYPE html>
<html lang="en">
<head>
<title>连接socket测试</title>
</head>
<body>
<script type="text/javascript">
var websocket = null;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/data-gather/websocket/running/info/1");
} else {
alert('当前浏览器 Not support websocket')
}
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
websocket.onopen = function () {
setMessageInnerHTML("登录成功,可以聊天咯");
}
websocket.onmessage = function (event) {
setMessage(event.data);
}
websocket.onclose = function () {
window.opener = null;
window.open('', '_self');
window.close();
}
window.onbeforeunload = function () {
closeWebSocket();
}
function closeWebSocket() {
websocket.close();
}
function setMessageInnerHTML(innerHTML) {
console.log(innerHTML);
}
function setMessage(innerHTML) {
console.log(innerHTML);
}
function send() {
var message = document.getElementById('info').value;
var data = {};
data.message = message;
data.type = 1;
websocket.send(JSON.stringify(data));
}
function sendImg(msg, type, fileName) {
var data = {};
data.message = msg;
data.type = type;
data.fileName = fileName;
websocket.send(JSON.stringify(data));
}
</script>
</body>
</html>
5 服务器端发送信息
WebSocketServer.sendInfo("1", "你好");
6 测试
1 启动springboot项目
2 打开html页面, F12, 看到控制台打印连接结果,并接收到信息即为成功