【发布时间】:2011-05-05 07:06:37
【问题描述】:
这是我的完整代码:cnx 已建立,我正在向服务器发送数据,但我无法从服务器读取任何内容...
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();
}
}
}
}
【问题讨论】:
-
我什么也没有得到:S什么都没发生...
-
这部分你调试了吗?您的
inFromServer是如何声明/处理的?您应该尝试捕获Exception而不是IOException,因为也很容易找到NullPointerException。此外,如果您的最后一行是一个空/空白字符串,您的TextViwe将不会显示任何内容。您应该尝试使用append而不是setText -
谢谢你rekaszeru...你给了我一个提示o解决我的问题。它起作用了,现在我可以读取我的数据了:D
标签: java android eclipse sockets client-side