2016-01-28 98 views
1

我有一個應用程序內功能,它應該向該應用程序的所有其他用戶發送消息。向所有應用程序用戶發送消息

這是我用它來聯繫我的服務器我的Java代碼:

public void sendToServer(final String text) { 


    new Thread(new Runnable() { 
     @Override 
     public void run() { 

      try { 

       String textParam = "text1=" + URLEncoder.encode(text, "UTF-8"); 

       String scriptUrlString = "http://www.example.com/example.php" 


       URL scriptUrl = new URL(scriptUrlString); 
       HttpURLConnection connection = (HttpURLConnection) scriptUrl.openConnection(); 
       connection.setDoOutput(true); 
       connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
       connection.setFixedLengthStreamingMode(textParam.getBytes().length); 
       OutputStreamWriter contentWriter = new OutputStreamWriter(connection.getOutputStream()); 
       contentWriter.write(textParam); 
       contentWriter.flush(); 
       contentWriter.close(); 

       InputStream answerInputStream = connection.getInputStream(); 
       final String answer = getTextFromInputStream(answerInputStream); 


       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         textView.setText(answer); 
        } 
       }); 
       answerInputStream.close(); 
       connection.disconnect(); 



      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    }).start(); 


} 

public String getTextFromInputStream(InputStream inputStream){ 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
    StringBuilder stringBuilder = new StringBuilder(); 

    String line; 
    try { 
     while ((line = bufferedReader.readLine()) != null){ 
      stringBuilder.append(line); 
      stringBuilder.append("\n"); 

     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return stringBuilder.toString().trim(); 
} 

在我的服務器我已經運行PHP腳本:

<?php 
$text = $_POST["text1"]; 
$content = $_POST["inhalt"]; 
if($text != null){ 
    $logfile = fopen("logfile.txt", "a"); 
    $date = date("d.m.Y H:i:s"); 
    fwrite($logfile, $date." Text: ".$text.$content"\n"); 
    fclose($logfile); 
}else{ 
    echo("No Text"); 
} 
?> 

所有這些工作完全正常,我回來我發送給服務器的文本。但我想要的是將此文本發送給應用程序的所有用戶。這是甚至是正確的方式,還是應該嘗試一些完全不同的東西。

在此先感謝,對不起我的英文不好,我是德國人。

+0

實施推送通知。 – Rohit5k2

+0

我有那個imlemented,但這不是我的問題 – Dan

回答

0

接收客戶郵件的當前方法是正確的。但爲了讓其他客戶接受這種方法,您需要使用其他方法。這種方法應詢問服務器是否有新消息,服務器應該使用該數據進行響應。應該儘可能經常調用此方法,因爲您希望更新消息。此方法應該與您當前的上傳消息方法相似。所以這個想法是:

客戶端發送消息到服務器。

- >服務器將消息保存在文件系統中。

所有客戶詢問是否有一段時間有新消息。

- >當服務器有特定客戶端的未讀消息時,它會以此作爲響應。

- >Server作爲閱讀客戶端X.應當標註在文件系統,消息

我希望你明白我的意思,並知道如何將其代碼:)如果沒有,隨意地問: )

+0

謝謝。我會盡我所能,如果我做不到,我會問你:D – Dan

相關問題