2017-09-21 173 views
0

我已經使用這個code來編寫websocket客戶端在java中。這是一個安全的插座。到目的地的連接建立正常,但onMessage沒有被調用。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); 
     } 
    } 
} 
+0

您可能缺少'@ OnMessage'中的'Session session'參數。簽名應該是'public void myMethod(Session session,String message);' – Al1

+0

嘗試將會話會話作爲方法的第一個參數,但它仍然不起作用。 –

回答

0

我能夠連接通過傳遞憑據

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(); 

我記錄在下面鏈接的步驟,以確保WebSocket的。

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