2016-12-15 96 views
1

現在在OkHttp 3.5中包含web套接字,我希望它可以使用。但我有一個問題,如果我不使用應用程序平均30分鐘,套接字斷開連接。爲什麼,我怎麼能做到「永恆」的連接?第二個問題,我如何檢查套接字連接?OkHttp 3.5 webSocket不保留連接

Singlton類

public class ServerSocket { 

    @Singleton 
    public OkHttpClient getOkHttpClient(){ 
     return new OkHttpClient(); 
    } 

    @Singleton 
    public Request getRequest(){ 
     return new Request.Builder() 
       .url(Link.url_socket) 
       .build(); 
    } 


} 

我的連接類:

OkHttpClient client = serverSocket.getOkHttpClient(); 
     Request request = serverSocket.getRequest(); 

     WebSocketListener webSocketListener = new WebSocketListener() { 
      @Override 
      public void onOpen(WebSocket webSocket, Response response) { 
       super.onOpen(webSocket, response); 
       Log.e("connect socket", "connect socket"); 
      } 

      @Override 
      public void onMessage(WebSocket webSocket, String text) { 
       super.onMessage(webSocket, text); 
       Log.e("onMessage", text); 
      } 

      @Override 
      public void onMessage(WebSocket webSocket, ByteString bytes) { 
       super.onMessage(webSocket, bytes); 
       Log.e("onMessage", "onMessage"); 
      } 

      @Override 
      public void onClosing(WebSocket webSocket, int code, String reason) { 
       super.onClosing(webSocket, code, reason); 
       Log.e("onClosing", "onClosing"); 
      } 

      @Override 
      public void onClosed(WebSocket webSocket, int code, String reason) { 
       super.onClosed(webSocket, code, reason); 
       Log.e("onClosed", "onClosed"); 
      } 

      @Override 
      public void onFailure(WebSocket webSocket, Throwable t, Response response) { 
       super.onFailure(webSocket, t, response); 
       Log.e("onFailure", "onFailure"); 
      } 
     }; 

     socket = client.newWebSocket(request, webSocketListener); 

回答