vue3与SpringBoot的socket.io连接

vue3与SpringBoot的socket.io连接

相关依赖

前端Vue3使用 [email protected]

npm install [email protected]

后端SpringBoot使用 [email protected]

<dependency>
	<groupId>com.corundumstudio.socketiogroupId>
	<artifactId>netty-socketioartifactId>
	<version>1.7.18version>
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()));
    }
}

前端代码实现


参考链接

netty-socketio概述 https://blog.csdn.net/u014635374/article/details/115893751
vue3使用socketio的简单例子
https://blog.csdn.net/autumn_later/article/details/123045541

你可能感兴趣的:(spring,spring,boot,vue,websocket)