springboot实现websocket服务端搭建,URL带参数连接(超详细)
在Spring Boot中实现WebSocket服务端并允许URL中带参数连接,你可以使用Spring的@ServerEndpoint
注解来定义WebSocket端点,并且可以在连接建立时处理URL中的参数。
以下是一个简单的例子:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
- 创建WebSocket端点并处理连接:
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriTemplate;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocketEndpoint {
// 保存所有的连接会话
private static final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
sessions.put(userId, session);
try {
// 连接建立时,可以根据userId进行逻辑处理
System.out.println("Connected: " + session.getId() + " for userId: " + userId);
} catch (IOException e) {
e.printStackTrace();
}
}
@OnClose
public void onClose(Session session, @PathParam("userId") String userId) {
sessions.remove(userId);
System.out.println("Disconnected: " + session.getId() + " for userId: " + userId);
}
@OnMessage
public void onMessage(String message, @PathParam("userId") String userId) {
// 处理接收到的消息
System.out.println("Received Message from userId: " + userId + " - " + message);
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("Error for Session: " + session.getId() + " - " + error.getMessage());
}
}
- 确保你的Spring Boot应用启动类上添加了
@EnableWebSocket
注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
@SpringBootApplication
@EnableWebSocket
public class WebSocketAp
评论已关闭