2015-04-20 126 views
1

我有一個連接到服務器的服務。此服務是Google通知的備份。我用C#編寫了客戶端,現在我想在Android中做類似的事情。服務器關閉或崩潰時自動重新連接到服務器

這是C#客戶端的代碼,如果服務器關閉,獲取異常時間並嘗試重新連接五分鐘(如果超過五次),那麼它將停止嘗試重新連接5分鐘,然後再試一次。這似乎是偉大的工作

代碼:

catch (Exception e) 
      { 
       Console.WriteLine("CONNECT " + e.Message); 
       if (attempts == 0) 
       { 
        connect_time = DateTime.Now; 
        interval_time = connect_time.AddMinutes(1); 
       } 

        double minutes = DateTime.Now.Subtract(connect_time).TotalMinutes; 


        if (minutes < 5.0) 
        { 
         System.Threading.Thread.Sleep(5000); 


         attempts++; 

        } 
        else 
        { 

         System.Threading.Thread.Sleep(300000); 
         continue; 
        } 


        resetConnectionEvent.Set(); 

      } 
     } 
     while (!stopConnections); 

現在我想這樣做Android的類似的東西。事情是我沒有在Android的ManualResetEvent,這是一個服務。這是我的Android代碼的現在:

class connectSocket implements Runnable 
{ 

    @Override 
    public void run() 
    { 
     do 
     { 
     try 
     { 
      IsRunning = true; 

      SSLContext context = SSLContext.getDefault(); 

      socket = context.getSocketFactory().createSocket(SERVERIP, SERVERPORT); 

      SSLSocketFactory sf = SSLSocketFactory.getSocketFactory(); 

      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

      socket2 = (SSLSocket) sf.createSocket(socket, SERVERIP, SERVERPORT, false); 

      HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); 

      SSLSession s = socket2.getSession(); 




      Intent text_intent = new Intent("Text_view"); 


      // 
      String MACAddr = Utils.getMACAddress(SocketServiceController.this,"eth0"); 
      if (MACAddr.length() == 0) 
       MACAddr = Utils.getMACAddress(SocketServiceController.this,"wlan0"); 
      if (MACAddr.length() == 0) 
       MACAddr = Secure.getString(SocketServiceController.this.getContentResolver(),Secure.ANDROID_ID); 
      System.out.println("************" + MACAddr); 
      // 
      out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket2.getOutputStream())), true); 

      out.write("0002:" + MACAddr + "\r\n"); 
      // 

      // 

      out.flush(); 

      try 
      { 
       InputStream inputstream = socket2.getInputStream(); 

       BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream)); 


       readObject = reader.readLine(); 

       String text = ""; 

       while(readObject != "") 
       { 
        text = readObject; 


        createNotification("Alert", text, SocketServiceController.this); 



        sendBroadcast(text_intent); 

        readObject = reader.readLine(); 
       } 
       connection_attemp = 0; 
      } 
      catch(Exception ex) 
      { 

       IsRunning = false; 
       createNotification("Alert","Connection is Closed", SocketServiceController.this); 
       stopService(new Intent(getApplicationContext(), SocketServiceController.class)); 
       IsRunning = false; 
       if(connection_attemp == 0) 
       { 
        c = Calendar.getInstance(); 
        connect_time=c.get(Calendar.MINUTE); 


       } 
       double minutes = c.get(Calendar.MINUTE)- connect_time; 

       if(minutes < 5.0) 
       { 

        connection_attemp++; 
        System.out.println("MINUTES: " + minutes + " CONNECT TIME: " + connect_time); 
        Thread.sleep(5000); 

        System.out.println("CONNECTIO ATTEMPT : " + connection_attemp); 
       } 
       else 
       { 
        System.out.println("SLEEPING"); 
        Thread.sleep(15000); 

       } 
       System.out.println("STARTING NEW SERVICE"); 

         startService(new Intent(getApplicationContext(), SocketServiceController.class)); 

      } 





     } 
     catch(Exception ex) 
     { 
      ex.printStackTrace(); 

      IsRunning = false; 

      try 
      { 
       if(IsRunning != false) 
        socket.close(); 

      } 
      catch(IOException e1) 
      { 
       e1.printStackTrace(); 
      } 
     } 
     IsRunning = false; 
     } 
     while(!IsRunning); 

我已經看到了有關使用旗語在計算器上的一些問題,但我不熟悉它,它是否會在這種情況下工作。現在,當我運行這段代碼時,它有點做我想做的事情,但是我創建了多個連接,而不是像第一次啓動服務時那樣只創建1個連接。而只是爲了清楚起見,這裏是我的OnStartCommand:

public int onStartCommand(Intent intent, int flags, int startId) { 
    // TODO Auto-generated method stub 
    super.onStartCommand(intent, flags, startId); 

    Runnable connect = new connectSocket(); 

    if(IsRunning == true) 
    { 

    } 
    else 
    { 
     new Thread(connect).start(); 
    } 

    return START_STICKY; 
} 

任何幫助,將不勝感激

回答

1

首先,我不認爲你需要一個信號燈,信號燈會如果您需要管理多個連接使用並且您需要確保這些連接不會同時執行。

對於第二點,run方法的所有代碼都在do-while循環中,這就是創建多個連接的原因,必須將套接字的所有配置放在循環外部,內部catch塊是處理服務器重新連接的一個,它應該是你使用循環的唯一部分。

相關問題