2013-06-26 2 views
0

나는 서버 측에 Jetty WebSockets를, 클라이언트 측에 Autobahn Android를 사용하고있다.Autobahn Android : 서버와의 연결을 끊는 방법

서버와 클라이언트 간의 간단한 연결이 정상적으로 작동합니다. 하지만 연결 상실을 처리하려고 할 때 약간의 문제가 있습니다.

안드로이드에

, 내가 가진 것은 이것이다 :

private void connectToServer() { 

     try { 

      mConnection.connect(getString(R.string.server_addr), new WebSocketHandler(){ 

       // connection au serveur 
       @Override 
       public void onOpen(){ 
        Log.d(TAG, "Connected"); 
        Log.d(TAG, "First connexion, sending MAC @"); 
        Log.d(TAG, "My MAC Addr: "+ macAddr); 
        mConnection.sendTextMessage(macAddr); 

       } 
       // reception d'un message text 
       @Override 
       public void onTextMessage(String payload) { 

        //TODO 
       } 

       // fermeture de la connexion 
       @Override 
       public void onClose(int code, String reason) { 
        Log.d(TAG, "Connection lost. "+reason); 
        if(mConnection.isConnected()){ 
         Log.d(TAG, "Still connected, disconnect!"); 
         mConnection.disconnect(); 
        } 
        if(code<4000){ 
         int totalWaitTime = 0; 
         int waitTime = 0; 
         Log.d(TAG, "Should be disconnected"); 
         while(!mConnection.isConnected()){ 
          try { 
           waitTime= random.nextInt(MAX_TO_WAIT - MIN_TO_WAIT + 1) + MIN_TO_WAIT; 
           Log.d(TAG, "I'll wait "+waitTime+"ms"); 
           totalWaitTime +=waitTime; 
           Log.d(TAG, "Waiting for "+totalWaitTime+"ms"); 
           if(totalWaitTime <= HOUR_TO_MS){ 
            Thread.sleep(waitTime); 
            Log.d(TAG, "Trying to reconnect"); 
            connectToServer(); 
           }else{ 
            throw new InterruptedException("Attempt to connect to the server during 1 hours without success"); 
           } 
          } catch (InterruptedException e) { 
           e.printStackTrace(); 
          } 
         } 
        } 
       } 
      }); 
     } catch (WebSocketException e) { 

      Log.e(TAG, "Error on connect: "+e.toString()); 
      Log.d(TAG, "is connected: "+mConnection.isConnected()); 
      if(mConnection.isConnected()) 
       mConnection.disconnect(); 
      connectToServer(); 
     } 

    } 

그리고 난 항상, 항상 같은 오류가 있습니다

06-26 10:36:07.823: E/wingo.stb.qos.AutoStartService(1842): Error on connect: de.tavendo.autobahn.WebSocketException: already connected 

을하지만 당신이 볼 수있는 것처럼, 내가 (으로 onClose에서 연결을 닫습니다) 및 WebSocketException이 catch 된 경우. 이 방법이 실제로 효과가 있습니까? 아니면 내가 잘못하고있는거야?

그런데, mConnection은 최종입니다. 어쩌면 여기서 문제가 생길 수 있습니까? 내가 연결 손실이있을 때

서버에서
private final WebSocketConnection mConnection = new WebSocketConnection(); 

, 나는 수동으로 세션을 닫습니다

@OnWebSocketClose 
    public void onClose(Session session, int closeCode, String closeReason){ 
      try { 
       System.out.println("connexion closed. Reason: "+closeReason); 
       pingPongTimer.cancel(); 
       if(session.isOpen()) 
        session.close(); 
       WebSocketsCentralisation.getInstance().leave(this); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
    } 

덕분에 멋진 사람들이 사전에!

+0

이 줄을 추가하십시오. mConnection = null; –

+0

@ Poovizhirajan.N : 나는 그것을 할 수 없습니다 mConnection은 마지막입니다! – brunettia

+0

ok 기다려라. chk 및 telu –

답변

0

내가 뭘 말하면 좀 지저분 해. 내가 지금 뭘 작동 :

private void connectToServer() { 
      try { 
       mConnection.connect(getString(R.string.server_addr), new WebSocketHandler(){ 

        // connection au serveur 
        @Override 
        public void onOpen(){ 
         Log.d(TAG, "Connected"); 
         Log.d(TAG, "First connexion, sending MAC @"); 
         Log.d(TAG, "My MAC Addr: "+ macAddr); 
         mConnection.sendTextMessage(macAddr); 

        } 
        // reception d'un message text 
        @Override 
        public void onTextMessage(String payload) { 

         //TODO 
        } 

        // fermeture de la connexion 
        @Override 
        public void onClose(int code, String reason) { 
         Log.d(TAG, "Connection lost. "+reason+" error code : "+code); 
         if(code<4000){ 
          reconnectToServer(); 
         } 
        } 
       }); 
      } catch (WebSocketException e) { 

       Log.e(TAG, "Error on connect: "+e.toString()); 
       Log.d(TAG, "is connected: "+mConnection.isConnected()); 
      } 

     } 

    private void reconnectToServer() { 
      try { 
       if(goConnect){ 
        goConnect = false; 
        Thread.sleep(1000); 
        Log.d(TAG, "DISCONNECT:"); 
        // mConnection.disconnect(); 
        Log.d(TAG, "ReconnectTimer Launched"); 
        new ReconnectTask().run(); 
       } 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      }  
      } 

    private class ReconnectTask extends TimerTask{ 
     @Override 
     public void run() { 
      try{ 
       if(totalWaitTime<HOUR_TO_MS){ 
        if(!mConnection.isConnected()){ 
         int waitTime= random.nextInt(MAX_TO_WAIT - MIN_TO_WAIT + 1) + MIN_TO_WAIT; 
         Log.d(TAG, "Next tentative to connect in "+waitTime+" ms"); 
         totalWaitTime +=waitTime; 
         reconnectTimer.schedule(new ReconnectTask(), waitTime); 
         connectToServer(); 
        }else{ 
         Log.d(TAG, "Connected to the server again"); 
         reinitializeReconnection(); 
        } 
       }else throw new InterruptedException("Attempt to connect to the server during 1 hours without success"); 
      }catch(InterruptedException e){ 
       Log.d(TAG, e.getMessage()); 
      } 

     } 
    } 

private void reinitializeReconnection(){ 
     reconnectTimer.purge(); 
     goConnect = true; 
     totalWaitTime = 0; 
    } 

기본적으로, 나는 모든 것을 WebSocketHandler에서 얻으려고했다. 그리고 내가 이해하지 못했던 것은 "onClose"에서 서버에 연결하려고 시도하고 서버가 다운되면 "onClose"로 다시 이동한다는 것입니다. 그래서 재귀 호출을하고 있었는데 정말 엉망이었습니다.

+0

안녕하세요, 내가 어떻게 reconnectTimer 개체를 인스턴스화할까요? – onizukaek

관련 문제