SocketService.java
16.2 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package com.qnbar.smc.service;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.gimi.common.cinema.model.MessageEvent;
import com.gimi.common.cinema.model.RoomInfo;
import com.gimi.common.cinema.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.xgimi.smartscreen.encrypt.AuthCode;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.Socket;
import java.util.Arrays;
public class SocketService extends Service {
private static final String TAG = "BackService";
private static final long HEART_BEAT_RATE = 20 * 1000;
public static final int JUST_OPEN_DOOR = 1701;
public static final int USER_OPEN_DOOR_AND_GET_MOVIE = 1703;
public static final int USER_OPEN_DOOR = 1704;//get the movie again charge show new movie
// public static final int USER_OPEN_DOOR_AND_GET_MOVIE = 1703;
/*
* 10001 //服务器发送了命令(带命令的返回消息),这个一般是服务器主动发消息的时候code为这个值
10002 //连接(认证)失败
10003 //还未注册连接就进行认证
10004 //终端编号未传
10005 //心跳异常,没有找到房间连接信息
10006 //心跳异常,连接标识符不一致
10007 //收到未知命令
10008 //收到无法解析的消息
10009 //已经认证过了,不允许再认证
*/
private static final int SUCCESS_MESSAGE = 10000;
private static final int AUTHENTICATION_FAILED = 10002; //连接(认证)失败
private static final int CONNECTION_BEFORE_AUTHENTICATION = 10003;//还未注册连接就进行认证
private static final int NOT_SEND_ROOM_SN = 10004;//终端编号未传
private static final int HEART_BEAR_ERROR = 10005; //心跳异常,没有找到房间连接信息
private static final int HEART_BEAR_ERROR_SYMBOL = 10006;//心跳异常,连接标识符不一致
private static final int OPEN_DOOR = 50001;//开门命令
private static final int ROOM_HAS_REGISTERED = 1001;
private static final int ROOM_NOT_EXIST_M = 1002;
private static final int HEAT_BEAT_RTN = 1003;
// public static final String HOST = "10.10.4.6";// "192.168.1.21";//
// public static final int PORT = 9501;
public static final String HOST = "10.10.4.6";// "192.168.1.21";//
// public static final int PORT = 8899;
public static final int PORT = 9501;
public static final String END_SYMBOL = "\\r\\n\\r\\n";//心跳包内容
// public String testRoomSn = "R170413034374";
public String testRoomSn = "c";
private ReadThread mReadThread;
private HeatBeatThread mHeatBeatThread;
private Gson gson;
// private LocalBroadcastManager mLocalBroadcastManager;
private WeakReference<Socket> mSocket;
// For heart Beat
// private Handler mHandler = new Handler();
// private Runnable heartBeatRunnable = new Runnable() {
//
// @Override
// public void run() {
// if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
// Log.d(TAG, "heart beat");
// boolean isSuccess = sendMsg(new Gson().toJson(new SocketSendMsg().contractHeartBeatMsg(testRoomSn)) + END_SYMBOL);//就发送一个HEART_BEAT_STRING过去 如果发送失败,就重新初始化一个socket
// if (!isSuccess) {
// Log.d(TAG, "heart beat error restart");
// mHandler.removeCallbacks(heartBeatRunnable);
// mReadThread.release();
// mHeatBeatThread.release();
// releaseLastSocket(mSocket);
// new InitSocketThread().start();
// }
// } else {
// Log.d(TAG, "heart beat less than beat rate");
// }
// mHandler.postDelayed(this, HEART_BEAT_RATE);
// }
// };
private long sendTime = 0L;
private Context context;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
gson = new Gson();
context = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String roomInfoStr = Utils.getString(this, "room-info");
if (!TextUtils.isEmpty(roomInfoStr)) {
Log.d("room-info", "room info not null");
RoomInfo roomInfo = null;
try {
roomInfo = gson.fromJson(roomInfoStr, RoomInfo.class);
Log.d("room-info", "room info room_sn update");
testRoomSn = roomInfo.getData().getRoom_sn();
} catch (JsonSyntaxException e) {
Log.d("room-info", "room gson parse exception return");
Toast.makeText(this, "房间信息配置出错,请重新进入应用获取", Toast.LENGTH_SHORT).show();
e.printStackTrace();
return super.onStartCommand(intent, flags, startId);
}
} else {
Log.d("room-info", "room info not exist");
Toast.makeText(this, "没有获取到房间信息,请查看后台配置", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
// }
new InitSocketThread().start();
Log.d(TAG, "socket service onCreate");
return super.onStartCommand(intent, flags, startId);
}
public boolean sendMsg(String msg) {
if (null == mSocket || null == mSocket.get()) {
return false;
}
Log.d(TAG, "send msg:" + msg);
Socket soc = mSocket.get();
try {
if (!soc.isClosed() && !soc.isOutputShutdown()) {
OutputStream os = soc.getOutputStream();
String message = msg;
os.write(message.getBytes());
os.flush();
sendTime = System.currentTimeMillis();//每次发送成数据,就改一下最后成功发送的时间,节省心跳间隔时间
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private void initSocket() throws IOException {//初始化Socket
Socket so = new Socket(HOST, PORT);
mSocket = new WeakReference<Socket>(so);
mReadThread = new ReadThread(so);
mReadThread.start();
// new Thread(heartBeatRunnable).start();
// mHandler.post(heartBeatRunnable);//初始化成功后,就准备发送心跳包
mHeatBeatThread = new HeatBeatThread(so);
mHeatBeatThread.start();//上面的 one plus 3t NetworkOnMainThreadException!!!
}
private void releaseLastSocket(WeakReference<Socket> mSocket) {
try {
if (null != mSocket) {
Socket sk = mSocket.get();
if (!sk.isClosed()) {
sk.close();
}
sk = null;
mSocket = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
class InitSocketThread extends Thread {
@Override
public void run() {
super.run();
try {
initSocket();
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "init socket thread error,restart again after 10's");
try {
Thread.sleep(HEART_BEAT_RATE);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
this.run();
}
}
}
private String varifyMsg = "";
// Thread to read content from Socket
class ReadThread extends Thread {
private WeakReference<Socket> mWeakSocket;
private boolean isStart = true;
public ReadThread(Socket socket) {
mWeakSocket = new WeakReference<Socket>(socket);
}
public void release() {
isStart = false;
releaseLastSocket(mWeakSocket);
}
@Override
public void run() {
super.run();
Socket socket = mWeakSocket.get();
if (null != socket) {
try {
if (!sendRegister) {
Log.d(TAG, "send register mes");
SocketSendMsg ssm = new SocketSendMsg().contractRegisterMsg(testRoomSn);
String msg = gson.toJson(ssm) + END_SYMBOL;
sendMsg(msg);
Log.d(TAG, "" + msg);
sendRegister = true;
}
Log.d(TAG, "send register mes end");
InputStream is = socket.getInputStream();
byte[] buffer = new byte[1024 * 4];
int length = 0;
while (!socket.isClosed() && !socket.isInputShutdown()
&& isStart && ((length = is.read(buffer)) != -1)) {
if (length > 0) {
String message = new String(Arrays.copyOf(buffer,
length)).trim();
Log.d(TAG, "end:" + message.contains(END_SYMBOL) + "");
Log.d(TAG, "recv msg:" + message);
try {
if (message.endsWith(END_SYMBOL)) {
message = message.replace(END_SYMBOL, "");
}
SocketResponse socketResponse = gson.fromJson(message/*.substring(0, message.length() - 8)*/, SocketResponse.class);
switch (socketResponse.getCode()) {
case SUCCESS_MESSAGE:
Log.d(TAG, "success:" + socketResponse.getCmd());
if (!TextUtils.isEmpty(socketResponse.getData().getVerify())) {
varifyMsg = AuthCode.getDecodeStr(socketResponse.getData().getVerify());
SocketSendMsg ssm = new SocketSendMsg().contractVerifyMsg(testRoomSn, varifyMsg);
String msg = gson.toJson(ssm) + END_SYMBOL;
sendMsg(msg);
}
break;
case OPEN_DOOR:
if (socketResponse.getData() != null) {
switch (socketResponse.getData().getUser()) {
//10用户,20管理员,默认值为0
case 10:
if (socketResponse.getData().getFirst() == 1) {
openDoor(USER_OPEN_DOOR_AND_GET_MOVIE, "user first open the door");
} else {
openDoor(USER_OPEN_DOOR, "user open the door");
}
break;
case 20:
openDoor(JUST_OPEN_DOOR, "administrator open the door");
break;
case 0:
openDoor(JUST_OPEN_DOOR, "get zero none user or administrator open the door");
break;
default:
openDoor(JUST_OPEN_DOOR, "none user or administrator open the door");
break;
}
}
break;
default:
Log.d(TAG, "print msg:" + socketResponse.toString());
}
if (("openDoor").equals(socketResponse.getCmd())) {
MessageEvent messageEvent = new MessageEvent();
messageEvent.setEventId(JUST_OPEN_DOOR);
messageEvent.setMessage("click item");
EventBus.getDefault().post(messageEvent);
}
} catch (JsonSyntaxException e) {
Log.d(TAG, message);
e.printStackTrace();
}
//收到服务器过来的消息,就通过Broadcast发送出去
// if (message.equals(END_SYMBOL)) {//处理心跳回复
// Intent intent = new Intent(HEART_BEAT_ACTION);
// mLocalBroadcastManager.sendBroadcast(intent);
// } else {
// //其他消息回复
// Intent intent = new Intent(MESSAGE_ACTION);
// intent.putExtra("message", message);
// mLocalBroadcastManager.sendBroadcast(intent);
// }
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void openDoor(int type, String msg) {
MessageEvent messageEvent = new MessageEvent();
messageEvent.setEventId(type);
messageEvent.setMessage(msg);
EventBus.getDefault().post(messageEvent);
}
boolean sendRegister = false;
// Thread to read content from Socket
class HeatBeatThread extends Thread {
private WeakReference<Socket> mWeakSocket;
private boolean isStart = true;
public HeatBeatThread(Socket socket) {
mWeakSocket = new WeakReference<Socket>(socket);
}
public void release() {
isStart = false;
releaseLastSocket(mWeakSocket);
}
@Override
public void run() {
super.run();
Socket socket = mWeakSocket.get();
if (null != socket) {
while (isStart) {
if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
Log.d(TAG, "heart beat:" + Thread.currentThread().getId());
boolean isSuccess = sendMsg(new Gson().toJson(new SocketSendMsg().contractHeartBeatMsg(testRoomSn)) + END_SYMBOL);//就发送一个HEART_BEAT_STRING过去 如果发送失败,就重新初始化一个socket
if (!isSuccess) {
Log.d(TAG, "heart beat error restart:" + Thread.currentThread().getId());
// mHandler.removeCallbacks(heartBeatRunnable);
mReadThread.release();
mHeatBeatThread.release();
sendRegister = false;
releaseLastSocket(mSocket);
new InitSocketThread().start();
}
} else {
Log.d(TAG, "heart beat less than beat rate:" + Thread.currentThread().getId());
}
try {
Thread.sleep(HEART_BEAT_RATE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
@Override
public void onDestroy() {
Log.d(TAG, "socket service destroy");
super.onDestroy();
}
}