[netty-websocket-boot-starter] 基于Netty的轻量级、高性能的WebSocket框架

简介

这是一个轻量级、高性能的基于 Netty 的 WebSocket 框架,提升你的 WebSocket 开发体验,为 Spring Boot 带来全新的 WebSocket 功能。 该项目使你可以轻松集成 WebSocket 到你的 Spring Boot 项目中,提供了 Tomcat WebSocket 的简单性,同时享受 Netty 性能和可扩展性的优势。
项目地址

主要特点

  • 无缝集成Spring Boot
  • 轻量级和高性能
  • 简化实时应用程序开发
  • 基于强大的Netty框架构建

在项目中添加依赖

        <dependency>
            <groupId>io.github.avidbytegroupId>
            <artifactId>netty-websocket-boot-starterartifactId>
            <version>1.0.0version>
        dependency>

新增 websocket 服务类

@Slf4j
@Service
@ServerEndpoint("/chat/text")
public class TextWebSocket {
    private static final Map<String, Session> CLIENTS = new ConcurrentHashMap<>();


    @BeforeHandshake
    public void handshake(Session session, HttpHeaders headers) {
        String token = headers.get("token");
        System.out.println("token:" + token);
    }

    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        if (!StringUtils.hasLength(username)) {
            log.error("username is empty");
            return;
        }
        log.info("username={}", username);
        session.setAttribute("name", username);
        CLIENTS.put(username, session);
    }

    @OnClose
    public void onClose(Session session){
        String name = session.getAttribute("name");
        CLIENTS.remove(name);
        session.close();
    }

    @OnMessage
    public void onMessage(Session session, String message){
        log.info("message={}", message);
        String ping = "ping";
        if (ping.equals(message)) {
            session.sendText("pong");
        }
    }

    @OnEvent
    public void onEvent(Session session, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    log.info("read idle");
                    break;
                case WRITER_IDLE:
                    log.info("write idle");
                    break;
                case ALL_IDLE:
                    log.info("all idle");
                    break;
                default:
                    break;
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error){
        String name = session.getAttribute("name");
        log.error("A communication error occurred and the connection was closed = {}", name);
        CLIENTS.remove(name);
        session.close();
    }

    public void sendMessageTo(String message, Session session) {
        session.sendText(message);
    }

    public void sendMessageAll(String message) {
        for (Session session : CLIENTS.values()) {
            session.sendText(message);
        }
    }

}

你可能感兴趣的:(websocket,网络协议,网络)