Spring-boot 集成 SocketIO(看这一篇就够了)
    		       		warning:
    		            这篇文章距离上次修改已过421天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中集成Socket.IO,你可以使用spring-boot-starter-web和spring-boot-starter-socket.io依赖。以下是集成Socket.IO的步骤和示例代码:
- 添加Maven依赖到你的pom.xml文件:
<dependencies>
    <!-- Spring Boot Web Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Boot Socket.IO Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-socket.io</artifactId>
        <version>2.6.0</version> <!-- 使用最新的版本 -->
    </dependency>
</dependencies>- 配置SocketIOServer:
import io.socket.socketio.server.SocketIOServer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class SocketIOConfig {
 
    @Bean
    public SocketIOServer socketIOServer() {
        return new SocketIOServer(9090); // 默认端口是9090,你可以更改为其他端口
    }
}- 创建一个控制器来处理Socket.IO事件:
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.springframework.stereotype.Component;
 
@Component
public class SocketIOController {
 
    @OnConnect
    public void onConnect(SocketIOClient client) {
        System.out.println("Client connected: " + client.getSessionId());
    }
 
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        System.out.println("Client disconnected: " + client.getSessionId());
    }
 
    @OnEvent("message")
    public void onMessage(SocketIOClient client, AckRequest request, String message) {
        client.sendEvent("message", "Received: " + message);
    }
}- 最后,确保你的Spring Boot应用程序启动类上有@EnableSocketIO注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.an
评论已关闭