Socket-Io 🏊‍

文档

客户端:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="./socket.js" type="text/javascript" charset="utf-8"></script>
    <title>Document</title>
  </head>
  <body>
    <h1>哈哈哈哈</h1>
    <script>
      const socket = io("http://127.0.0.1:8090", {
        path: "/ws",
        query: "token=xxxxxx891919sjsau*._doao",
        transports: ["websocket", "xhr-polling", "jsonp-polling"]
      });

      socket.on("connect", () => {
        console.log("连接成功.........");
      });

      socket.on("disconnect", () => {
        console.log("断开连接........");
      });

      socket.on("event1", msg => {
        console.log(msg);
      });

      socket.on("event2", msg => {
        console.log(msg);
      });

      socket.emit("event1", "我要event1");

      socket.emit("event2", "我要event2");
    </script>
  </body>
</html>

服务端: Netty-SocketIo

配置:

@Configuration
@Slf4j
@Order(1)
public class WebSocketConfig {

    /*@Bean
    public ServerEndpointExporter serverEndpointExporter() {  //war包不需要注入这个对象
        return new ServerEndpointExporter();
    }*/

    @Bean
    public SocketIOServer socketIOServer() {
        //tcp配置
        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setTcpKeepAlive(true);
        socketConfig.setTcpNoDelay(true);

        com.corundumstudio.socketio.Configuration configuration = new com.corundumstudio.socketio.Configuration();

        configuration.setSocketConfig(socketConfig);
        //configuration.setHostname(""); 默认0.0.0.0
        configuration.setPort(8090);//监听端口
        configuration.getSocketConfig().setReuseAddress(true);

        configuration.setBossThreads(1);
        configuration.setWorkerThreads(100);

        configuration.setAllowCustomRequests(true);
        configuration.setOrigin("*");
        configuration.setTransports(Transport.POLLING, Transport.WEBSOCKET);
        configuration.setWebsocketCompression(true);
        configuration.setContext("/ws");

        //权限校验
        configuration.setAuthorizationListener(new AuthorizationListener() {
            @Override
            public boolean isAuthorized(HandshakeData data) {
                boolean flag = false;

                List<String> token = data.getUrlParams().get("token");
                //.....
                return true;
            }
        });


        return new SocketIOServer(configuration);
    }

}

需要注解的话: 开启注解扫描

/**
    * 用于扫描netty-socketio的注解,比如 @OnConnect、@OnEvent
    */
   @Bean
   public SpringAnnotationScanner springAnnotationScanner() {
       return new SpringAnnotationScanner(socketIOServer());
   }

监听处理:

@Service
@Slf4j
@Order(2)
public class SocketIoService {
    //事件
    private static final String EVENT1 = "event1"; //1
    private static final String EVENT2 = "event2"; //2
    private static Map<String, SocketIOClient> clients = new ConcurrentHashMap<>();
    private final SocketIOServer socketIOServer;

    @Autowired
    public SocketIoService(SocketIOServer socketIOServer) {
        this.socketIOServer = socketIOServer;
    }

    //服务启动
    @PostConstruct
    public void autoStart() {
        try {
            //绑定监听事件
            socketIOServer.addConnectListener(client -> connect(client));//连接
            socketIOServer.addDisconnectListener(client -> disConnect(client));//断开连接
            // 事件1
            socketIOServer.addEventListener(EVENT1, String.class, new DataListener<String>() {
                @Override
                public void onData(SocketIOClient client, String data, AckRequest ackSender) throws Exception {
                    event1(client, data, ackSender);
                }
            });

            //事件2
            socketIOServer.addEventListener(EVENT2, String.class, new DataListener<String>() {
                @Override
                public void onData(SocketIOClient client, String data, AckRequest ackSender) throws Exception {
                    event2(client, data, ackSender);
                }
            });
            socketIOServer.start();
            log.info("******socket io 服务已启动!!*********监听客户端连接***********");
        } catch (Exception e) {
            log.error("************socket io 服务启动失败!!*********", e);
        }
    }


    //监听连接
    public void connect(SocketIOClient client) {
        log.info("新客户端连接");
    }

    //断开
    public void disConnect(SocketIOClient client) {
        log.info("客户端断开");
    }

    // 事件1
    public void event1(SocketIOClient client, String data, AckRequest ackSender) {
        client.sendEvent(EVENT1, "event1111.........");
        System.out.println(111);
    }

    // 事件2
    private void event2(SocketIOClient client, String data, AckRequest ackSender) {
        client.sendEvent(EVENT2, "event222.........");
        System.out.println(222);
    }


    //停止服务
    @PreDestroy
    public void destroy() {
        log.info("********socket io 服务要停止了*********");
        socketIOServer.stop();
        log.info("********socket io 服务已经停止了*********");
    }
}
上次更新: 4 个月前