尝试调用实现客户端线程的类时强制关闭
我在 Android 上有一个客户端服务器应用程序,两者都在同一台机器上运行。 在我的客户端应用程序的第一个活动中,我尝试调用应该连接到服务器应用程序的客户端类,但我强制关闭。
这就是我在应用程序的第一个活动中调用客户端类的方式:
Thread cThread=new Thread(new ClientThread());
cThread.start();
这是我的客户端类:
public class ClientThread implements Runnable{
private Handler handler=new Handler();
Socket socket;
private TextView clientState;
public void run()
{
try
{
InetAddress serverAddr=InetAddress.getByName("10.0.2.2");
handler.post(new Runnable(){
public void run(){
clientState.setText(" try to connect!");
}
});
socket=new Socket(serverAddr, 8080);
//connected=true;
handler.post(new Runnable(){
public void run(){
clientState.setText("Connected!");
}
});
}
catch(Exception e){
handler.post(new Runnable(){
public void run(){
clientState.setText("Error");
}
});
e.printStackTrace();
}
}
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
//out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
有人能告诉我出了什么问题吗,或者至少给我一个想法。 我应该说的一件事是,当客户端类集成到我的第一个活动中时,我的客户端工作正常 - 它连接到服务器(我的意思是,最初我没有客户端类,全部都在第一个活动中......并且它工作得很好)。 我来这里是为了了解更多详情! 提前谢谢你!
I have a client-sever app on android,both running on the same machine.
In the first activity of my client app I try to call client class which should connect to the server application,but I get force close.
This is how I call the client class in the first activity of my app:
Thread cThread=new Thread(new ClientThread());
cThread.start();
and here is my client class:
public class ClientThread implements Runnable{
private Handler handler=new Handler();
Socket socket;
private TextView clientState;
public void run()
{
try
{
InetAddress serverAddr=InetAddress.getByName("10.0.2.2");
handler.post(new Runnable(){
public void run(){
clientState.setText(" try to connect!");
}
});
socket=new Socket(serverAddr, 8080);
//connected=true;
handler.post(new Runnable(){
public void run(){
clientState.setText("Connected!");
}
});
}
catch(Exception e){
handler.post(new Runnable(){
public void run(){
clientState.setText("Error");
}
});
e.printStackTrace();
}
}
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
//out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can someone tell what is wrong or at least give me an ideea.
One thing that I should say is that my client works fine-it connects to the server,when the client class is integrated in my first activity(I mean,initially I had no client class was all in the first activity...and it worked fine).
I'm here for further details!
Thank u in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有堆栈跟踪,它看起来会崩溃,因为您没有初始化文本视图。
Without the stack trace it looks like it crashes cause you didn't initialize the textview.