vue3与SpringBoot的socket.io连接
相关依赖
前端Vue3使用 socket.io-client@2.2.0
npm install socket.io-client@2.2.0
后端SpringBoot使用 netty-socketio@1.7.18
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.18</version>
</dependency>
后端代码实现
Spring启动类
@SpringBootApplication
@Slf4j
public class MeetingApplication implements CommandLineRunner {
// 注入 SocketIOServer
@Autowired
private SocketIOServer socketIOServer;
public static void main(String[] args) {
SpringApplication.run(MeetingApplication.class, args);
}
// 将在springboot启动后运行run
@Override
public void run(String... args) throws Exception {
socketIOServer.start();
log.info("socket.io启动");
}
}
Socket.io配置类
@Configuration
class SocketIOConfig {
/**
* SocketIO配置
* @return
*/
@Bean
public SocketIOServer socketIoServer() {
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
config.setHostname("localhost");
config.setPort(9092);
return new SocketIOServer(config);
}
/**
* 用于扫描netty-socketio的抓取事件注解
*/
@Bean
public SpringAnnotationScanner springAnnotationScanner() {
return new SpringAnnotationScanner(socketIoServer());
}
}
Socket.io事件处理类
@Component
@Slf4j
public class SocketHandler {
// 连接成功就会调用此方法
@OnConnect
public void onConnect(SocketIOClient client){
client.sendEvent("message", "conn ok");
log.info(String.format("连接成功 %s",client.getSessionId()));
}
}
前端代码实现
<script setup>
import io from "socket.io-client";
var socket = io.connect("ws://localhost:9092", {
transports: ["websocket", "polling"], // 优先使用websocket连接方式
timeout: 5000,
});
// 监听message事件
socket.on("message", (message) => {
console.log(message);
});
</script>
参考链接
netty-socketio概述 https://blog.csdn.net/u014635374/article/details/115893751
vue3使用socketio的简单例子
https://blog.csdn.net/autumn_later/article/details/123045541