while (true) {
//获取当前网络信息
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifiNetInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//如果wifi是联通的
if (wifiNetInfo.isConnected()) {
// TODO Auto-generated method stub
super.run();
try {
Log.v("my_tag", "我要连接socket");
//建立socket
socket = new Socket(Myservice.ip, Myservice.poot);
//把socket包装成可读对象
bufferedReader = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
//把socket包装成可写类
printWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())), true);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.v("my_tag", e.toString());
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.v("my_tag", "重新尝试连接socket");
//如果socket异常,等待一会儿后重新开始连接
continue;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v("my_tag", e.toString());
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//令一种异常,有待研究啊
Log.v("my_tag", "重新尝试连接socket");
continue;
}
//连接成功发送一个信息
printWriter.println("hehe");
while (true) {
try {
//连接成功后发送心跳包,如果异常说明连接关闭
socket.sendUrgentData(0xFF);
// 心跳包发送成功,执行与服务器的交互代码
Log.v("my_tag", "socket正常");
conversationWithService();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//心跳包发送失败跳出发送心跳包和交互的循环执行socket死后的处理
break;
}
}
// 心跳包发送失败则关闭socket
Log.v("my_tag", "i have break");
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 如果没有WIFI网络则先休眠再循环
else {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
android写的一个客户端。。。
最新推荐文章于 2021-05-27 10:47:59 发布