springboot中怎么用socket模拟硬件数据并能够在前端页面显示
时间: 2023-05-26 19:05:21 浏览: 150
1. 首先在SpringBoot项目中引入WebSocket模块。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 在SpringBoot中创建WebSocket连接器和消息处理器。
- 连接器
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
```
- 处理器
```java
public class WebSocketHandler extends TextWebSocketHandler {
private WebSocketSession session;
@Override
public void afterConnectionEstablished(WebSocketSession session) {
this.session = session;
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理消息
}
}
```
3. 在SpringBoot中创建一个可以发送消息给前端页面的服务。
```java
@Service
public class WebSocketServer {
private WebSocketHandler wsHandler;
@Autowired
public void setWebSocketHander(WebSocketHandler handler) {
this.wsHandler = handler;
}
public void sendMessage(String message) throws IOException {
if (wsHandler.session != null && wsHandler.session.isOpen()) {
wsHandler.session.sendMessage(new TextMessage(message));
}
}
}
```
4. 接下来可以模拟硬件数据的发送,并将数据发送给前端页面。
```java
@Service
public class HardwareDataService {
private Boolean isSimulating = false;
@Autowired
private WebSocketServer wsServer;
public void startSimulating() {
this.isSimulating = true;
new Thread(() -> {
while (isSimulating) {
// 模拟硬件数据,这里假设温度数据每秒钟增加1度。
double temperature = getTemperature();
try {
// 将模拟数据推送到前端页面
wsServer.sendMessage("temperature:" + temperature);
Thread.sleep(1000);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public void stopSimulating() {
isSimulating = false;
}
// 模拟获取温度数据的方法
private double getTemperature() {
// ...
}
}
```
5. 最后在前端页面中创建一个WebSocket对象,并接收并处理推送过来的数据。
```javascript
var ws = new WebSocket("ws://localhost:8080/ws");
ws.onmessage = function(event) {
var message = event.data;
// 在页面中显示推送过来的数据
document.getElementById("temperature").innerHTML = message;
};
```
阅读全文