在前端想使用socket可以使用websocket,在这里提供另外一种方式来解决socket接收的数据在web前端显示的问题。
首先socket还是采用最常见的java语言中的socket类,这里需要将socket client置为Spring容器管理的类,这里将socket client置为service,并且为其配置一个list缓存接收到的数据,然后在controller中提供一个数据访问接口供ajax访问,并且添加一个runner,在Springboot启动的时候启动这个runner。
Talk is cheap,show me the code.
runner表示:
@Component
@Order(value = 1)
public class SocketRunner implements ApplicationRunner {//或者也可以实现这个接口CommandLineRunner
@Autowired
SocketClientImpl client;
@Override
public void run(ApplicationArguments args) throws Exception {
client.doWork();
}
}
client表示:
@Service
public class SocketClientImpl implements SocketClient {
@Autowired
private Position position;
@Override
public void doWork() {
Socket client = null;
InputStream inputStream = null;
OutputStream outputStream = null;
ObjectOutputStream writer

本文介绍了一种在前端使用WebSocket接收socket数据的方法,通过Spring Boot整合,实现数据的实时推送与显示。利用Java Socket客户端与Spring容器管理,创建了一个缓存数据的list,再通过Controller提供数据访问接口,最后在前端使用Ajax定时获取数据。
最低0.47元/天 解锁文章
687

被折叠的 条评论
为什么被折叠?



