這裏是我的全碼:CNX的建立,我將數據發送到服務器,但我不能從服務器讀取什麼...Android客戶端套接字如何讀取數據?
public class client extends Activity
{
/** Called when the activity is first created. */
Socket sock;
String spliter = "**";
String mobileNbr = "100";
String LastJOKEId = "-1";
String spliterlast = "^^$$";
BufferedReader inFromServer;
DataOutputStream outToServer;
TextView cnx;
TextView output;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupNetworking();
// Thread readerThread=new Thread(new IncomingReader());
// readerThread.start();
}
private void setupNetworking()
{
try
{
Log.i("ClientActivity", "Connecting...");
sock = new Socket("192.168.153.221", 9003);
cnx = (TextView) findViewById(R.id.textView1);
cnx.setText("Network Established.");
inFromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
Log.i("ClientActivity", "Sending command.");
outToServer = new DataOutputStream(sock.getOutputStream());
String sentence = "logins" + spliter + mobileNbr + spliter + LastJOKEId + spliterlast;
outToServer.writeBytes(sentence + '\n');
Log.i("ClientActivity", "Sent.");
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
cnx = (TextView) findViewById(R.id.textView1);
cnx.setText("Network failed");
e.printStackTrace();
}
}
public class IncomingReader implements Runnable
{
String message;
public void run()
{
try
{
while ((message = inFromServer.readLine()) != null)
{
output = (TextView) findViewById(R.id.textView2);
output.setText(message);
}
}
catch (IOException e)
{
output = (TextView) findViewById(R.id.textView2);
output.setText("nth to display");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
你會得到什麼結果? – 2011-05-05 07:10:59
我沒有得到任何東西:S什麼都沒發生... – AnthonyK 2011-05-05 07:15:54
你調試這部分?如何聲明/處理你的'inFromServer'?您應該嘗試捕獲Exception而不是IOException,因爲可能非常容易出現'NullPointerException'。另外,如果你的最後一行是一個空白/空白字符串,你的'TextViwe'不會顯示任何內容。你應該嘗試使用['append'](http://developer.android.com/reference/android/widget/TextView.html#append%28java.lang.CharSequence%29)而不是'setText' – rekaszeru 2011-05-05 07:23:03