亲测可用。
1.pom.xml
<!-- webSocket 开始-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-client-api</artifactId>
<version>1.1</version>
</dependency>
2.注入配置:
package com.simons.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfigOne {
/**
* 这个bean会自动注册使用了@ServerEndpoint注解声明的对象
* 没有的话会报404
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3. 服务端实现
package com.simons.websocket;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @ServerEndpoint 该注解可以将类定义成一个WebSocket服务器端,
* @OnOpen 表示有浏览器链接过来的时候被调用
* @OnClose 表示浏览器发出关闭请求的时候被调用
* @OnMessage 表示浏览器发消息的时候被调用
* @OnError 表示报错了
*/
@ServerEndpoint("/ws/serverOne")
@Component
public class WebSocketServerOne {
//concurrent包下线程安全的Set
public static CopyOnWriteArraySet<WebSocketServerOne> SESSIONS = new CopyOnWriteArraySet<>();
private Session session;
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
SESSIONS.add(this);
System.out.println(String.format("成功建立连接~ 当前总连接数为:%s", SESSIONS.size()));
System.out.println(this);
System.out.println("是否开启了:"+session.isOpen());
System.out.println("session通道是否存在?"+"sessonId:"+session.getId()+":"+(session.getAsyncRemote()!=null?"是":"否"));
}
@OnClose
public void onClose(Session session) {
// SESSIONS.remove(this);
System.out.println("是否开启了:"+session.isOpen());
System.out.println("session通道是否存在?"+"sessonId:"+session.getId()+":"+(session.getAsyncRemote()!=null?"是":"否"));
System.out.println(String.format("成功关闭连接~ 当前总连接数为:%s", SESSIONS.size()));
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println(message);
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 指定发消息
*
* @param message
*/
public void sendMessage(String message) {
try {
this.session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 群发消息
*
* @param message
*/
public static void fanoutMessage(String message) {
SESSIONS.forEach(ws -> ws.sendMessage(message));
}
}
4.前端实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webSocket</title>
<style type="text/css">
</style>
</head>
<body>
<h1>WebSocket Demo.</h1>
<h1>WebSocket Demo..</h1>
<h1>WebSocket Demo...</h1>
<input type="button" onclick="websocket.send('666666666')" value="点我发消息"/>
<input type="button" onclick="websocket.close()" value="关闭"/>
</body>
<script type="application/javascript">
var websocket = {
send: function (str) {
}
};
window.onload = function () {
if (!'WebSocket' in window) return;
webSocketInit();
};
function webSocketInit() {
websocket = new WebSocket("ws://127.0.0.1:8080/ws/serverOne");
//成功建立连接
websocket.onopen = function () {
setMessageInnerHTML("成功连接到服务器");
};
//接收到消息
websocket.onmessage = function (event) {
console.log(event.data)
};
//连接发生错误
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接关闭
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
};
//监听窗口关闭事件,当窗口关闭时,主动关闭websocket连接
// window.onbeforeunload = function () {
// websocket.close()
// };
}
</script>
</html>
5.跑一个定时器查看一下服务器每个连接Session的状态
package com.simons.websocket;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import javax.websocket.Session;
import java.util.Iterator;
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class Jobs {
//3.添加定时任务
// @Scheduled(cron = "0/5 * * * * ?")
//或直接指定时间间隔,例如:5秒
@Scheduled(fixedRate=1000*2)
private void configureTasks() {
System.out.println("定时任务开始");
Iterator it = WebSocketServerOne.SESSIONS.iterator();
while (it.hasNext()) {
WebSocketServerOne webSocketServerOne = (WebSocketServerOne) it.next();
Session session = webSocketServerOne.getSession();
System.out.println(session.getId()+":"+ session.isOpen());
// System.out.println(str);
}
}
}
|