<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.0</version>
</dependency>
WebSocketConfig配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
Ccontroller接口
import com.alibaba.fastjson2.JSONObject;
import com.rise.common.utils.StringUtils;
import com.rise.domain.ProTriaxialData;
import com.rise.service.IProTriaxialDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
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.List;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/websocket")//表示将该类标识为一个 WebSocket 服务端端点,客户端可以通过该端点进行 WebSocket 连接。/websocket 是客户端连接的 URL 路径。
@EnableScheduling//表示启用 Spring 的定时任务调度功能。在该类中使用的 @Scheduled 注解才能生效。
@Component//表示将该类标识为一个 Spring 组件,由 Spring 自动进行管理和注入。
public class MyWebSocket {
private static final Logger log = LoggerFactory.getLogger(MyWebSocket.class);
private static int onlineCount = 0;
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
private Session session;
private Boolean isReceive = true;
private Double lat = 36.679071;
//业务注入
private static IProTriaxialDataService proTriaxialDataService;
@Autowired
public void proTriaxialDataService(IProTriaxialDataService proTriaxialDataService){
//WebScoketController是该类的类名 需要换成自己的类名
MyWebSocket.proTriaxialDataService = proTriaxialDataService;
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
addOnlineCount();
log.info("有新链接加入!当前在线人数:{}",getOnlineCount());
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
subOnlineCount();
log.info("有一链接关闭!当前在线人数:{}",getOnlineCount());
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
log.info("socket 接收到信息{}",message);
//判断前端是否已消费上一条信息
if (StringUtils.isNotEmpty(message) && message.equals("已消费")){
isReceive = true;
} else {
// 连接已断开
isReceive = false;
}
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
@Scheduled(cron = "*/2 * * * * *")
public void sendMessageScheduledTask()throws Exception{
log.info("socket 执行三数据推送给前端");
try{
if (isReceive){
//测试数据
ProTriaxialData data = new ProTriaxialData();
data.setId(1);
data.setLng(117.175169);
data.setLat(lat);
data.setWeight(13.96);
data.setCarNumber("鲁A·88888");
lat = lat + 0.001;
if(lat>36.69){
lat = 36.679071;
}
//每2秒发送一次
// List<ProTriaxialData> proTriaxialData = proTriaxialDataService.selectProTriaxialDataByCreateTimeDesc();
// if (proTriaxialData!=null && proTriaxialData.size()>0){
String message = JSONObject.toJSONString(data);
for (MyWebSocket item : webSocketSet) {
item.sendMessage(message);
}
// }
}
log.info("socket 数据发送成功!");
}catch (Exception e){
log.info("socket 数据发送失败!");
e.printStackTrace();
}
}
public static synchronized int getOnlineCount() {
return MyWebSocket.onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
initWebSocket(){
let that = this;
var ws = new WebSocket("ws://IP:PORT/websocket");
// 连接成功后的回调函数
ws.onopen = function (params) {
console.log('客户端连接成功')
// 向服务器发送消息
ws.send('认证成功!')
};
// 从服务器接受到信息时的回调函数
ws.onmessage = function (e) {
console.log('收到服务器响应', e.data)
var data = e.data;
if(data!=undefined){
if(data.indexOf("{") != -1){
var obj = JSON.parse(data);
//接收后台发送的消息数据做后续处理
}else{
console.log(data);
}
}
};
// 连接关闭后的回调函数
ws.onclose = function(evt) {
console.log("关闭客户端连接");
};
// 连接失败后的回调函数
ws.onerror = function (evt) {
console.log("连接失败了",evt);
};
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,这样服务端会抛异常。
window.onbeforeunload = function() {
ws.close();
}
console.log(ws)
},
如果发现连接不通可能需要在后台接口将url设置白名单
更多【网络-Websocket + Vue使用】相关视频教程:www.yxfzedu.com