Token导航 LogoToken导航TokenDH.com
研究检索操作浏览器github未标认证来源可访问许可证需确认审计通过

spring-websocket弹簧网络套接字

Agent Skill

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

总安装

624

周安装

26

GitHub Stars

12

下载量

208
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:spring-websocket(弹簧网络套接字)
来源仓库:https://github.com/claude-dev-suite/claude-dev-suite
仓库路径:skills/spring-websocket
安装命令:
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill spring-websocket
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill spring-websocket

简介

在 Spring 应用中集成 WebSocket 协议,实现全双工实时通信。

  • 适用于聊天室、实时通知或协同编辑等需要长连接的场景。
  • 支持 STOMP 子协议和消息广播、点对点发送模式。
  • 需考虑连接保活、消息序列化和跨域安全策略配置。spring-websocket 属于研究检索类 Skill,可作为该场景下的辅助能力补充。
  • 技能来源为 claude-dev-suite 开源项目模块。

SKILL.md

Spring WebSocket

Quick Start

<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // Prefix for messages from server to clients (subscribe)
        registry.enableSimpleBroker("/topic", "/queue");
        // Prefix for messages from clients to server
        registry.setApplicationDestinationPrefixes("/app");
        // Prefix for private messages to a specific user
        registry.setUserDestinationPrefix("/user");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
            .setAllowedOrigins("http://localhost:3000")
            .withSockJS();  // Fallback for browsers without WebSocket
    }
}

Message Controller

@Controller
@RequiredArgsConstructor
@Slf4j
public class ChatController {

    private final SimpMessagingTemplate messagingTemplate;

    // Receives message and broadcasts to all subscribers of /topic/chat
    @MessageMapping("/chat.send")
    @SendTo("/topic/chat")
    public ChatMessage sendMessage(ChatMessage message, Principal principal) {
        message.setSender(principal.getName());
        message.setTimestamp(Instant.now());
        return message;
    }

    // Direct reply to the sender
    @MessageMapping("/chat.echo")
    @SendToUser("/queue/reply")
    public ChatMessage echoMessage(ChatMessage message) {
        message.setContent("Echo: " + message.getContent());
        return message;
    }

    // Programmatic send to a specific user
    @MessageMapping("/chat.private")
    public void sendPrivateMessage(PrivateMessage message, Principal principal) {
        message.setSender(principal.getName());
        messagingTemplate.convertAndSendToUser(
            message.getRecipient(),
            "/queue/private",
            message
        );
    }

    // Broadcast to all
    public void broadcastNotification(NotificationMessage notification) {
        messagingTemplate.convertAndSend("/topic/notifications", notification);
    }
}
// DTOs
public record ChatMessage(
    String id, String sender, String content,
    Instant timestamp, MessageType type
) {}

public enum MessageType { CHAT, JOIN, LEAVE, TYPING }

public record PrivateMessage(
    String sender, String recipient, String content, Instant timestamp
) {}

Event Handlers

@Component
@RequiredArgsConstructor
@Slf4j
public class WebSocketEventListener {

    private final SimpMessagingTemplate messagingTemplate;
    private final OnlineUserService onlineUserService;

    @EventListener
    public void handleSessionConnected(SessionConnectedEvent event) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = accessor.getSessionId();
        Principal principal = accessor.getUser();

        if (principal != null) {
            String username = principal.getName();
            onlineUserService.userConnected(username, sessionId);
            messagingTemplate.convertAndSend("/topic/users.online",
                new UserStatusMessage(username, UserStatus.ONLINE));
        }
    }

    @EventListener
    public void handleSessionDisconnect(SessionDisconnectEvent event) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = accessor.getSessionId();

        onlineUserService.findBySessionId(sessionId).ifPresent(username -> {
            onlineUserService.userDisconnected(sessionId);
            messagingTemplate.convertAndSend("/topic/users.online",
                new UserStatusMessage(username, UserStatus.OFFLINE));
        });
    }
}
Full Reference: See security.md for complete security configuration and validation.

Security Essentials

@Configuration
@EnableWebSocketSecurity
public class WebSocketSecurityConfig {

    @Bean
    public AuthorizationManager<Message<?>> messageAuthorizationManager(
            MessageMatcherDelegatingAuthorizationManager.Builder messages) {
        return messages
            .nullDestMatcher().permitAll()
            .simpSubscribeDestMatchers("/topic/public/**").permitAll()
            .simpSubscribeDestMatchers("/topic/**", "/queue/**").authenticated()
            .simpDestMatchers("/app/**").authenticated()
            .anyMessage().authenticated()
            .build();
    }
}
Full Reference: See security.md for JWT auth, CSRF protection, and message validation.

Session Attributes & Headers

@Controller
public class ChatController {

    @MessageMapping("/chat.join")
    @SendTo("/topic/chat")
    public ChatMessage joinChat(
            @Payload JoinRequest request,
            @Header("simpSessionId") String sessionId,
            SimpMessageHeaderAccessor headerAccessor) {

        // Save attributes in the WebSocket session
        headerAccessor.getSessionAttributes().put("username", request.username());
        headerAccessor.getSessionAttributes().put("roomId", request.roomId());

        return new ChatMessage(null, request.username(),
            request.username() + " joined!", Instant.now(), MessageType.JOIN);
    }
}

Error Handling

@ControllerAdvice
public class WebSocketExceptionHandler {

    @MessageExceptionHandler
    @SendToUser("/queue/errors")
    public ErrorMessage handleException(Exception e) {
        return new ErrorMessage("ERROR", e.getMessage(), Instant.now());
    }

    @MessageExceptionHandler(AccessDeniedException.class)
    @SendToUser("/queue/errors")
    public ErrorMessage handleAccessDenied(AccessDeniedException e) {
        return new ErrorMessage("ACCESS_DENIED",
            "You don't have permission", Instant.now());
    }
}

public record ErrorMessage(String code, String message, Instant timestamp) {}

Heartbeat Configuration

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic", "/queue")
            .setHeartbeatValue(new long[]{10000, 10000})  // Server, Client in ms
            .setTaskScheduler(heartBeatScheduler());
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Bean
    public TaskScheduler heartBeatScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(1);
        scheduler.setThreadNamePrefix("ws-heartbeat-");
        scheduler.initialize();
        return scheduler;
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
        registry.setMessageSizeLimit(128 * 1024)      // 128KB max message
            .setSendBufferSizeLimit(512 * 1024)       // 512KB send buffer
            .setSendTimeLimit(20 * 1000);             // 20s send timeout
    }
}
Full Reference: See brokers.md for RabbitMQ and Redis external broker configuration.

Best Practices

DoDon't
Use STOMP + SockJS for cross-browserUse raw WebSocket only
Implement heartbeat for disconnect detectionRely on TCP keepalive
Use external broker (RabbitMQ) for scalingUse simple broker in production
Validate payload before processingTrust client input
Handle disconnections properlyKeep state in memory only

When NOT to Use This Skill

  • REST APIs - Use spring-rest skill
  • Simple SSE - Use SseEmitter endpoints
  • NestJS WebSocket - Use nestjs-websocket skill
  • React client - Use react-websocket skill for frontend

Anti-Patterns

Anti-PatternProblemSolution
Connection refusedEndpoint not configuredVerify registerStompEndpoints
403 ForbiddenCORS not configuredAdd setAllowedOrigins
No sessionPrincipal nullConfigure WebSocket authentication
Simple broker in prodNo horizontal scalingUse RabbitMQ/Redis adapter
State in memoryLost on restartUse external session store

Quick Troubleshooting

ProblemDiagnosticFix
Connection refusedCheck endpoint configVerify registerStompEndpoints
403 ForbiddenCheck CORSAdd setAllowedOrigins
Principal is nullCheck auth configImplement AuthChannelInterceptor
Message too largeCheck size limitsIncrease setMessageSizeLimit
Heartbeat timeoutCheck intervalsConfigure heartbeat properly

Reference Files

FileContent
brokers.mdRabbitMQ, Redis external broker configuration
security.mdJWT Auth, CSRF, Message Validation
advanced.mdLow-level WebSocket, JS Client, Testing

External Documentation

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.47%
按下载量换算78

Claude

32.32%
按下载量换算67

Cursor

18.16%
按下载量换算38

Gemini CLI

9.57%
按下载量换算20

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills