套接字.IO-client Java 与 Header

Socket.IO-client Java with Header

我有需要 user-id 才能连接的套接字服务器。因此,我需要将 extraHeader 设置为连接构造函数。我尝试了以下代码,但没有运气。请帮我打通,谢谢。

添加额外的 header 'x-user-id': userId 到连接构造函数

private Socket mSocket;
{
    try {
        IO.Options opts = new IO.Options();
        mSocket = IO.socket(socket_url, opts);
        mSocket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {

                Transport transport = (Transport)args[0];
                transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        @SuppressWarnings("unchecked")
                        Map<String, List<String>> headers = (Map<String, List<String>>)args[0];
                        // modify request headers
                        headers.put("x-user-id", Arrays.asList("5B59F68B7B7811E88C3E52964BF487E4"));
                    }
                }).on(Transport.EVENT_RESPONSE_HEADERS, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                    }
                });
            }
        });

    } catch (URISyntaxException e) {}
}

这是我的 swift 有效代码。

private init(){
        self.socketManager = SocketManager(socketURL: URL(string:"\(MAIN_URL)/message")!, config: [.log(true),.extraHeaders(["x-user-id":AppManager.instance.userId])])
        self.socket = socketManager?.defaultSocket
    }

您也可以使用 Spring 框架提供的 stomp 客户端。 要编译和 运行 以下方法,您应该将 'spring-messaging' 和 'spring-websocket' maven 依赖项添加到您的项目中。

public ListenableFuture<StompSession> connect() {
    List<Transport> transports = new ArrayList<>(2);
    transports.add(new WebSocketTransport(new StandardWebSocketClient()));
    transports.add(new RestTemplateXhrTransport());

    SockJsClient sockJsClient = new SockJsClient(transports);
    sockJsClient.setMessageCodec(new Jackson2SockJsMessageCodec());

    WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
    headers.add("x-user-id", "5B59F68B7B7811E88C3E52964BF487E4");

    return stompClient.connect(socket_url, headers, new StompSessionHandlerAdapter() {});
}

问题已在服务器端修复。这是我的配置。 添加此 >>>

var server = app.listen(3000, {// options can go here
  transports: ['xhr-polling']
});
io.use((socket, next) => {
  let clientId = socket.handshake.headers['x-user-id'];
});