2012-12-30 232 views
0

我對android和java編程很新穎。我正在編寫一個服務器客戶端連接。我的電腦應該是服務器,我的android智能手機應該是客戶端。服務器很好。我可以從客戶端向服務器發送消息,但是我無法從服務器向客戶端發送消息。當我這樣做時,客戶端會粉碎並關閉自己。我真的希望任何人都能幫助我解決我的大問題。Android客戶端沒有收到消息

這裏是我的活動:

package com.example.sercerclient2zweidreidrei; 

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 


public class MyActivity extends Activity { 

Button btn; 
EditText textOut; 
TextView textIn; 
TextView problems; 
Button send; 
private TCPClient myTcpClient; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    final EditText editText = (EditText) findViewById(R.id.editText); 
    final TextView textIn = (TextView) findViewById(R.id.textin); 
    Button send = (Button)findViewById(R.id.send_button); 

    // connect to the server 
    new connectTask().execute(""); 

    send.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      String message = editText.getText().toString(); 

      //sends the message to the server 
      if (myTcpClient != null) { 
       myTcpClient.sendMessage(message); 
      } 
     } 
    }); 
} 

public class connectTask extends AsyncTask<String,String,TCPClient> { 

    @Override 
    protected TCPClient doInBackground(String... message) { 

     //we create a TCPClient object and 
     myTcpClient = new TCPClient(new TCPClient.OnMessageReceived() { 

      @Override 
      //here the messageReceived method is implemented 
      public void messageReceived(String message) { 
       //this method calls the onProgressUpdate 
       publishProgress(message); 
      } 
     }); 
     myTcpClient.run(); 

     return null; 
    } 

    @Override 
    protected void onProgressUpdate(String... values) { 
     super.onProgressUpdate(values); 

     //in the arrayList we don't add the message received from server 
     //here i try to write the incomming message into a textVie 
     textIn.setText(values[0]); 
    } 
} 
} 

這裏是我的TcpClient類:

package com.example.sercerclient2zweidreidrei; 

import android.util.Log; 
import java.io.*; 
import java.net.InetAddress; 
import java.net.Socket; 


public class TCPClient { 

private String serverMessage; 
public static final String SERVERIP = "192.168.2.107"; //your computer IP address 
public static final int SERVERPORT = 4444; 
private OnMessageReceived mMessageListener = null; 
private boolean mRun = false; 

PrintWriter out; 
BufferedReader in; 

/** 
* constructor of the class. OnMessageReceived listens for the messages 
* received from server 
*/ 
public TCPClient(OnMessageReceived listener) { 
    mMessageListener = listener; 
} 

/** 
* Sends the message entered by client to the server 
* @param message text entered by client 
*/ 
public void sendMessage(String message){ 
    if (out != null && !out.checkError()) { 
     out.println(message); 
     out.flush(); 
    } 
} 

public void stopClient() { 
    mRun = false; 
} 

public void run() { 
    mRun = true; 

    try { 
     // here you must put your computer's IP address. 
     InetAddress serverAddr = InetAddress.getByName(SERVERIP); 

     Log.e("TCP Client", "C: Connecting..."); 

     //create a socket to make the connection with the server 
     Socket socket = new Socket(serverAddr, SERVERPORT); 

     try { 
      //send the message to the server 
      out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); 

      Log.e("TCP Client", "C: Sent."); 
      Log.e("TCP Client", "C:Done."); 

      //receive the message which the server sends back 
      in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

      //in this while the client listens for the messages send by the server 
      while (mRun) { 
       serverMessage = in.readLine(); 

       if (serverMessage != null && mMessageListener != null) { 
        //call the method messageReceived from MyActivity class 
        mMessageListener.messageReceived(serverMessage); 
       } 
       serverMessage = null; 
      } 

      Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'"); 

     } catch (Exception e) { 

      Log.e("TCP", "S: Error", e); 

     } finally { 
      //the socket must be closed. It is not possible to reconnect to this socket 
      //after it is closed, which means a new socket instance has to be created. 
      socket.close(); 
     } 
    } catch (Exception e) { 
     Log.e("TCP", "C:Error", e); 
    } 
} 

/* 
* Declare the interface. The method messageReceived(String message must be 
* implemented in the MyActivity class at on asynckTask doInBackground 
*/ 
public interface OnMessageReceived { 
    public void messageReceived(String message); 
} 
} 

最後在這裏你可以看到我的main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MyActivity" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentTop="true" 
    android:text="@string/Textausgabe" /> 

<EditText 
    android:id="@+id/editText" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_below="@+id/textView1" 
    android:layout_marginTop="34dp" 
    android:ems="10" > 

    <requestFocus /> 
</EditText> 

<Button 
    android:id="@+id/send_button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignRight="@+id/textView1" 
    android:layout_below="@+id/editText" 
    android:layout_marginTop="26dp" 
    android:text="@string/Senden" /> 

<TextView 
    android:id="@+id/textin" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_centerVertical="true" 
    android:text="@string/EinkommenderText" 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

</RelativeLayout> 

這裏是我的logcat :

12-30 16:36:37.340:I/dalvikvm(548):主題ID = 3:反應以信號3

12-30 16:36:37.560:I/dalvikvm(548):寫棧跟蹤爲 '/data/anr/traces.txt'

12-30 16:36:37.740:I/dalvikvm(548):主題ID = 3:反應以信號3

12-30 16點36: 37.790:I/dalvikvm(548):將堆棧跟蹤寫入'/data/anr/traces.txt'

12-30 16:36:38.350:D/gralloc_goldfish(548):未檢測到GPU仿真的仿真器。

12-30 16:36:38.630:I/dalvikvm(548):主題ID = 3:反應以信號3

12-30 16:36:38.650:I/dalvikvm(548):寫堆棧跡線到 '/data/anr/traces.txt'

12-30 16:36:39.721:E/TCP客戶端(548):C:連接...

12-30 16時36: 39.981:E/TCP客戶端(548):C:發送。 E/TCP客戶端(548):C:完成。

12-30 16:38:59.034:d/AndroidRuntime(548):關閉VM

12-30 16:38:59.034:W/dalvikvm(548):線程ID = 1:螺紋與離開未捕獲的異常 (組= 0x409c01f8)

12-30 16:38:59.051:E/AndroidRuntime(548):致命異常:主

12-30 16:38:59.051:E/AndroidRuntime(548 ):java.lang.NullPointerException

12-30 16:38:59.051:E/AndroidRuntime(548):at com.example.sercerclient2zweidreidrei.MyActivity $ connectTask.onProgressUpdate(MyActivity.java:72)

12-30 16:38:59.051:E/AndroidRuntime(548):在 com.example.sercerclient2zweidreidrei.MyActivity $ connectTask .onProgressUpdate(MyActivity.java:1)

12-30 16:38:59。051:E/AndroidRuntime(548):在 android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:618)

12-30 16:38:59.051:E/AndroidRuntime(548):在 機器人.os.Handler.dispatchMessage(Handler.java:99)

12-30 16:38:59.051:E/AndroidRuntime(548):在android.os.Looper.loop(Looper.java:137)

12-30 16:38:59.051:E/AndroidRuntime(548):在 android.app.ActivityThread.main(ActivityThread.java:4424)

12-30 16:38:59.051:E/AndroidRuntime(548):在 java.lang.reflect.Method.invokeNative(本機方法)

12-30 16:38:59.051:E/AndroidRuntime(548):在 java.lang.reflect.Method中。調用(Method.java:511)

12-30 16:38:59.051:E/AndroidRuntime(548):在 com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)

12-30 16:38:59.051:E/AndroidRuntime(548):在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)

12-30 16:38:59.051:E/AndroidRuntime(548):在dalvik.system.NativeStart.main(母語 方法)

12-30 16:38:59.752:I/dalvikvm(548):主題ID = 3:反應以信號3

12-30 16:38:59.900:I/dalvikvm(548):寫堆棧跟蹤到 '/data/anr/traces.txt'

希望你可以找到我的錯誤。

+0

您可能想考慮使用GCM將您的消息發送到您的設備。同時添加一些日誌代碼併發布結果可以幫助人們回答你。 – selsine

+0

發佈您的logcat – CocoNess

+0

我添加了我的LogCat,並希望有人可以在那裏找到我的錯誤。 – Lukas5060

回答

0

您在活動中使用AsyncTask任務來建立TCP連接。因此,一旦建立連接,就會發送消息,並且您的AsyncTask任務完成並關閉TCP連接。

您應該使用獨立服務而不是活動來保持連接處於打開狀態。

+0

[鏈接](http://myandroidsolutions.blogspot.de/2012/07/android-tcp-connection-tutorial.html)在那裏我發現它以類似的方式,它的工作。但在我的應用程序,我不會有這個列表視圖只是一個TextView。是不是有可能在TextView中顯示輸入消息? – Lukas5060

+0

當然有幾種可能性。你必須保持你已建立的連接。你是否想保持聯繫?在上面引用的示例中,連接保持不變。 – gezdy

+0

好的。這不是我想聽到的答案,但確定。如果這是唯一的方法。當我將手機切換到水平模式時,我的連接也會崩潰。使用AsyncTask可能導致這個問題嗎? – Lukas5060

相關問題