簡體   English   中英

為什么我的java服務器和android客戶端不能來回發送任何消息?

[英]Why can't my java server and android client send any message back and forth?

對於mmo我正在嘗試創建,我有一個連接到Java服務器的android客戶端。 當服務器在我的計算機上直接運行時,android正在模擬器上運行。 他們可以很好地連接並確認連接,但客戶端停在一個奇怪的地方,我無法弄清楚原因。

服務器的WorkerThread的Run方法:

public void run() {
    try {
        InputStream input  = clientSocket.getInputStream();
        OutputStream output = clientSocket.getOutputStream();
        String returns="";
        String s="";
        try{
        s= inputStreamToString(input).toString();
        }
        catch(Exception e)
        {}
       output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " +
               this.serverText + " - " +
               "").getBytes());
        output.close();
        input.close();
    } catch (IOException e) {
        //report exception somewhere.
        e.printStackTrace();
    }
}

InputStream stringbulider:

private static StringBuilder inputStreamToString(InputStream is) {
    String line = "";
    StringBuilder total = new StringBuilder();

    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (Exception e) {
    }

    return total;}

客戶端的連接方法:

      public String sendMessage(String message)
      {
try{        clientSocket = new Socket("10.0.2.2", 9000);

          String modifiedSentence;
          DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
          BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
          outToServer.writeBytes(message+"\n");
              //Stops here
          modifiedSentence = inFromServer.readLine();
          outToServer.close();
          inFromServer.close();
          clientSocket.close();
          Log.v(modifiedSentence, modifiedSentence);
          return modifiedSentence;}
catch(Exception e)
{
    return "";}

      }

謝謝,任何幫助將不勝感激。

編輯:更新,如果我關閉客戶端或服務器,另一個可以收到前者的消息,但如果兩者都打開,他們不能...

嘗試這個:

outToServer.writeBytes(message+"\n");
outToServer.flush(); // Flush output to socket
modifiedSentence = inFromServer.readLine();

還要檢查服務器是否實際收到了數據。

在執行寫入之后,一個好的做法是執行flush。
這會強制寫入套接字。
另外,我建議你將最后一部分放在最后部分
(我知道這與您的問題沒有關系,但我想幫助您更好地編碼。
因此,結合我的答案的代碼應該如下所示:

OutputStream outStream = .... //Get it somehow
try {
   outStream.write(data);
   outStream.flush();
   //Do other stuff if needed
} catch (Exception ex) {
 //Do something with the exception
}
finally {
   if (outStream != null) {
      try {
        outStream.close();
     } catch (IOException ioex) {
        //Ignore
     }
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM