springBoot2.0+vue实现websocket通信
- vue前端
created() { // 页面创建生命周期函数
this.initWebSocket()
},
destroyed: function () { // 离开页面生命周期函数
this.websocketclose();
},
methods: {
initWebSocket: function () {
// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
this.websock = new WebSocket("ws://localhost:8081/websocket/admin");
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
},
websocketonopen: function () {
console.log("WebSocket连接成功");
},
websocketonerror: function (e) {
console.log("WebSocket连接发生错误");
},
websocketonmessage: function (e) {
console.log(e.data); // console.log(e);
},
websocketclose: function (e) {
console.log("connection closed (" + e.code + ")");
}
- jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- java后端
@Component
@ServerEndpoint("/websocket/{username}")
//此注解相当于设置访问URL
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
private static Map<String,Session> sessionPool = new HashMap<String,Session>();
@OnOpen
public void onOpen(Session session, @PathParam(value="username")String username) {
this.session = session;
webSockets.add(this);
sessionPool.put(username, session);
System.out.println("【websocket消息】有新的连接,总数为:"+webSockets.size());
}
@OnClose
public void onClose() {
webSockets.remove(this);
System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
}
@OnMessage
public void onMessage(String message) {
System.out.println("【websocket消息】收到客户端消息:"+message);
}
// 此为广播消息
public void sendAllMessage(String message) {
for(WebSocket webSocket : webSockets) {
System.out.println("【websocket消息】广播消息:"+message);
try {
webSocket.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 此为单点消息 (发送文本)
public void sendTextMessage(String shopId, String message) {
Session session = sessionPool.get(shopId);
if (session != null) {
try {
session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 此为单点消息 (发送对象)
public void sendObjMessage(String shopId, Object message) {
Session session = sessionPool.get(shopId);
if (session != null) {
try {
session.getAsyncRemote().sendObject(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
- 其他地方调用
@Autowired private WebSocket webSocket;
//从对象存储获取左天的数据
@Scheduled(cron = "0 */1 * * * ?")
public void pushMsgToVue(){
Integer i = 0;
webSocket.sendTextMessage("admin", ""+(++i));
}
- 全局配置类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
借鉴:https://blog.csdn.net/Tomwildboar/article/details/90018967