有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java WebSocket:onMessage未被触发

我使用这个code用java编写websocket客户端。这是一个安全的插座。已建立到目标的连接,但未调用onMessage

当我用java脚本编写同样的东西时,它工作正常并且能够得到响应

请检查我的代码,并告知我遗漏了什么

我的代码:

@ClientEndpoint
public class MyClientEndpoint {
    @SuppressWarnings("unchecked")

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected to endpoint: " + session.getBasicRemote());
        try {
            JSONObject obj = new JSONObject();
            obj.put("subscribe", URLEncoder.encode("xxxxxxx","UTF-8"));
            String msg = obj.toJSONString();
            System.out.println("Sending message to endpoint: " + msg);
            session.getBasicRemote().sendText(msg);
        } catch (Exception ex) {
            Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @OnMessage
    public void onMessage(String message) {
    System.out.println("Received message in client: " + message);
        Client.messageLatch.countDown();
    }



public class Client {

    final static CountDownLatch messageLatch = new CountDownLatch(1);

    public static void main(String[] args) {
        try {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            String uri = "wss://api.....";
            System.out.println("Connecting to:: " + uri);
            container.connectToServer(MyClientEndpoint.class, URI.create(uri));
            messageLatch.await(10, TimeUnit.SECONDS);            
        } catch (DeploymentException | InterruptedException | IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我可以通过传入凭据连接到安全websocket

    ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
                 public void beforeRequest(Map<String, List<String>> headers) {
              String credentials = "username:password";
              headers.put("Authorization", Arrays.asList("Basic " + new BASE64Encoder().encode(credentials.getBytes())));
                     System.out.println("Header set successfully");
                 }
             };
    
             ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create()
                     .configurator(configurator)
                     .build();
    

    我在下面的链接中记录了这些步骤

    https://bigdatatechbytes.blogspot.in/2017/10/java-client-for-secure-web-socket.html