Java WebSocket:未触发onMessage

时间:2017-09-21 11:53:14

标签: java websocket java-websocket

我已使用此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 个答案:

答案 0 :(得分:0)

我可以通过传递

中的凭据来连接到安全的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