android写的一个客户端。。。

		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();
						}
					}
				}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值