Android基于Tcp协议的Socket长链接封装

在Service中使用,注意以下规则

1
2
3
4
//startService() 启动Service
其生命周期为context.startService() ->onCreate()- >onStart()->Service running-->context.stopService() | ->onDestroy() ->Service stop
//对于bindService()启动Service:
context.bindService()->onCreate()->onBind()->Service running-->onUnbind() -> onDestroy() ->Service stop

TcpSocketHelper封装类,使Socket保持长连接,便于手机跟服务器通讯,保持心跳实时更新数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package com.irobotcity.psnclient.net;

import android.text.format.DateFormat;
import android.util.Log;

import com.irobotcity.psnclient.listener.OnRecivedListener;
import com.irobotcity.psnclient.utils.LogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Calendar;
import java.util.Date;

/**
* 使用Socket封装长连接
* Created by Jerry on 2017/1/18.
*/

public class TcpSocketHelper {
private String mTag = "TcpSocketHelper";
private Socket socket;
private boolean _connect;
private ReceiveThread mReceiveThread;
private boolean receiveStop;
private Date lastKeepAliveOkTime;
private OnRecivedListener mRecivedListener;
private String mIpAddr = "192.168.1.137";
private int mPort = 9995;

/**
* 开启链接socket
* @param ipAddr
* @param port
*/
public void startConnect(String ipAddr, int port){
LogUtils.e(mTag, "准备链接...");
this.mIpAddr = ipAddr;
this.mPort = port;
InetAddress serverAddr;
try {
socket = new Socket(ipAddr, port);
_connect = true;
mReceiveThread = new ReceiveThread();
receiveStop = false;
mReceiveThread.start();
LogUtils.e(mTag, "链接成功...");

} catch (Exception e) {
LogUtils.e(mTag, "链接出错..." + e.getMessage().toString());
e.printStackTrace();
}
}

/**
* 关闭链接
*/
public void closeConnect(){
if (socket != null){
try {
socket.close();
socket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 保持心跳
*/
public void KeepAlive() {
// 判断socket是否已断开,断开就重连
if (lastKeepAliveOkTime != null) {
LogUtils.e(mTag, "上次心跳成功时间:"+ DateFormat.format("yyyy-MM-dd HH:mm:ss", lastKeepAliveOkTime));
Date now = Calendar.getInstance().getTime();
long between = (now.getTime() - lastKeepAliveOkTime.getTime());// 得到两者的毫秒数
if (between > 60 * 1000) {
LogUtils.e(mTag, "心跳异常超过1分钟,重新连接:");
lastKeepAliveOkTime = null;
socket = null;
}

} else {
lastKeepAliveOkTime = Calendar.getInstance().getTime();
}

if (!checkIsAlive()) {
LogUtils.e(mTag, "链接已断开,重新连接.");
startConnect(mIpAddr, mPort);
}
}

/**
* 此方法是检测是否连接
* @return
*/
public boolean checkIsAlive() {
if (socket == null||!socket.isConnected())
return false;
// try {
// socket.sendUrgentData(0xFF);
// } catch (IOException e) {
// return false;
// }
return true;

}

/**
* 发送数据的方法
* @param msg
*/
public void sendmessage(String msg) {
boolean isAlive = checkIsAlive();
if (!isAlive)
return;
LogUtils.e(mTag, "准备发送消息:" + msg);
try {
if (socket != null && socket.isConnected()) {
if (!socket.isOutputShutdown()) {

//2.得到socket读写流
OutputStream os=socket.getOutputStream();
//true:是否自动flush
PrintWriter outStream=new PrintWriter(os, true);
outStream.print(msg);
outStream.flush();
}
}
LogUtils.e(mTag, "发送成功!");
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 设置接收数据监听器
* @param mRecivedListener
*/
public void setmRecivedListener(OnRecivedListener mRecivedListener) {
this.mRecivedListener = mRecivedListener;
}

/**
* 数据接收线程
*/
class ReceiveThread extends Thread{

@Override
public void run() {
while (true) {
try {
sleep(500);
// LogUtils.i(mTag, "监听中...:"+socket.isConnected());
// 判断 Socket 是否处于连接状态
if (socket != null && socket.isConnected()) {
// 客户端接收服务器端的响应,读取服务器端向客户端的输入流
InputStream isRead = socket.getInputStream();
// 缓冲区
byte[] buffer = new byte[isRead.available()];
// 读取缓冲区
isRead.read(buffer);
// 转换为字符串
String responseInfo = new String(buffer);
// 日志中输出
if(responseInfo != null&&!responseInfo.equals("")){
Log.e("TcpManager", "返回:"+responseInfo);
mRecivedListener.onRecived(responseInfo);
}

lastKeepAliveOkTime = Calendar.getInstance().getTime();
KeepAlive();

continue;
} else {
if (socket != null)
LogUtils.e(mTag, "链接状态:" + socket.isConnected());
}

} catch (Exception e) {
LogUtils.e(mTag, "监听出错:" + e.toString());
e.printStackTrace();
}
}
}
}
}

以下是OnRecivedListener监听器

1
2
3
4
5
6
7
8
9
package com.irobotcity.psnclient.listener;

/**
* Created by Jerry on 2017/1/18.
*/

public interface OnRecivedListener {
public void onRecived(String data);
}