2

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

将额外的标头 '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) {}
}

这是我有效的快速代码。

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
    }
4

2 回答 2

2

您还可以使用 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() {});
}
于 2018-07-19T07:13:44.987 回答
0

该问题已在服务器端解决。这是我的配置。添加这个>>>

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