Commit 392bd186f7f6ee7559ba8bebb0a0c3ac7841136a

Authored by 钟易宏
1 parent bc654b29

1 add lock for socket

2 add recvMsg method for recv msg from socket
... ... @@ -99,8 +99,13 @@ public class SocketService1 extends BaseService {
99 99 private Gson gson;
100 100
101 101 private WeakReference<Socket> mSocket;
  102 + StringBuilder readingMsg = new StringBuilder();
  103 +
102 104 // For heart Beat
103 105 private Handler mHandler = new Handler();
  106 +
  107 + boolean sendRegister = false;
  108 +
104 109 private Runnable heartBeatRunnable = new Runnable() {
105 110
106 111 @Override
... ... @@ -113,7 +118,7 @@ public class SocketService1 extends BaseService {
113 118 mHandler.removeCallbacks(heartBeatRunnable);
114 119 mReadThread.release();
115 120 sendRegister = false;
116   - releaseLastSocket(mSocket);
  121 + releaseLastSocket();
117 122 new InitSocketThread().start();
118 123 }
119 124 }
... ... @@ -170,30 +175,32 @@ public class SocketService1 extends BaseService {
170 175 }
171 176
172 177 String roomInfoStr = Utils.getString(this, "room-info");
173   - if (!TextUtils.isEmpty(roomInfoStr)) {
174   - LogUtils.d("room-info", "room info not null");
175   - RoomInfo roomInfo = null;
176   - try {
177   - roomInfo = gson.fromJson(roomInfoStr, RoomInfo.class);
178   - LogUtils.d("room-info", "room info room_sn update");
179   - testRoomSn = roomInfo.getData().getRoom_sn();
180   - } catch (JsonSyntaxException e) {
181   - LogUtils.d("room-info", "room gson parse exception return");
182   - Toast.makeText(this, "房间信息配置出错,请重新进入应用获取", Toast.LENGTH_SHORT).show();
183   - e.printStackTrace();
184   - return super.onStartCommand(intent, flags, startId);
185   - }
186   - } else {
  178 + if (TextUtils.isEmpty(roomInfoStr)) {
187 179 LogUtils.d("room-info", "room info not exist");
188 180 Toast.makeText(this, "没有获取到房间信息,请查看后台配置", Toast.LENGTH_SHORT).show();
189 181 return super.onStartCommand(intent, flags, startId);
190 182 }
  183 +
  184 + LogUtils.d("room-info", "room info not null");
  185 + RoomInfo roomInfo = null;
  186 + try {
  187 + roomInfo = gson.fromJson(roomInfoStr, RoomInfo.class);
  188 + LogUtils.d("room-info", "room info room_sn update");
  189 + testRoomSn = roomInfo.getData().getRoom_sn();
  190 + } catch (JsonSyntaxException e) {
  191 + LogUtils.d("room-info", "room gson parse exception return");
  192 + Toast.makeText(this, "房间信息配置出错,请重新进入应用获取", Toast.LENGTH_SHORT).show();
  193 + e.printStackTrace();
  194 + return super.onStartCommand(intent, flags, startId);
  195 + }
  196 +
191 197 new InitSocketThread().start();
192 198 LogUtils.d(TAG, "socket service onCreate");
193 199 return START_STICKY;
194 200 }
195 201
196   - public boolean sendMsg(String msg) {
  202 + ///begin socket operation
  203 + public synchronized boolean sendMsg(String msg) {
197 204 if (null == mSocket || null == mSocket.get()) {
198 205 return false;
199 206 }
... ... @@ -217,7 +224,7 @@ public class SocketService1 extends BaseService {
217 224 return true;
218 225 }
219 226
220   - private void initSocket() throws IOException {//初始化Socket
  227 + private synchronized void initSocket() throws IOException {//初始化Socket
221 228 LogUtils.d(TAG, "serverHost:serverPort:" + serverHost + ":" + serverPort);
222 229 mHandler.post(new Runnable() {
223 230 @Override
... ... @@ -227,27 +234,59 @@ public class SocketService1 extends BaseService {
227 234 });
228 235 Socket so = new Socket(serverHost, serverPort);
229 236 mSocket = new WeakReference<>(so);
230   - mReadThread = new ReadThread(so);
  237 + readingMsg.setLength(0);
  238 + mReadThread = new ReadThread();
231 239 mReadThread.start();
232 240 }
233 241
234   -
235   - private void releaseLastSocket(WeakReference<Socket> mSocket) {
  242 + private synchronized void releaseLastSocket() {
236 243 try {
237 244 if (null != mSocket) {
238 245 Socket sk = mSocket.get();
239 246 if (!sk.isClosed()) {
240 247 sk.close();
241 248 }
242   - sk = null;
243   - mSocket = null;
244 249 }
245 250 } catch (IOException e) {
246 251 LogUtils.d(TAG, "error" + e.getMessage());
247 252 e.printStackTrace();
  253 + } finally {
  254 + readingMsg.setLength(0);
  255 + mSocket = null;
248 256 }
249 257 }
250 258
  259 + private synchronized boolean recvMsg(StringBuilder msg) {
  260 + Socket socket = mSocket.get();
  261 + if (null == socket) {
  262 + return false;
  263 + }
  264 + try {
  265 + InputStream is = socket.getInputStream();
  266 + byte[] buffer = new byte[1024];
  267 + int length = 0;
  268 + while (!socket.isClosed()
  269 + && !socket.isInputShutdown()
  270 + && ((length = is.read(buffer)) > 0)
  271 + ) {
  272 + String tmp = new String(Arrays.copyOf(buffer, length));
  273 + readingMsg.append(tmp);
  274 + int pos = readingMsg.indexOf(END_SYMBOL);
  275 + if (pos != -1) {
  276 + msg.setLength(0);
  277 + msg.append(readingMsg.substring(0, pos));
  278 + readingMsg.delete(0, pos + END_SYMBOL.length());
  279 + return true;
  280 + }
  281 + }
  282 + } catch (IOException e) {
  283 + e.printStackTrace();
  284 + return false;
  285 + }
  286 + return false;
  287 + }
  288 + ///end socket operation
  289 +
251 290 class InitSocketThread extends Thread {
252 291 @Override
253 292 public void run() {
... ... @@ -270,169 +309,170 @@ public class SocketService1 extends BaseService {
270 309
271 310 // Thread to read content from Socket
272 311 class ReadThread extends Thread {
273   - private WeakReference<Socket> mWeakSocket;
  312 +// private WeakReference<Socket> mWeakSocket;
274 313 private boolean isStart = true;
275 314
276   - public ReadThread(Socket socket) {
277   - mWeakSocket = new WeakReference<Socket>(socket);
278   - }
  315 +// public ReadThread() {
  316 +//// mWeakSocket = new WeakReference<Socket>(socket);
  317 +// }
279 318
280 319 public void release() {
281 320 isStart = false;
282   - releaseLastSocket(mWeakSocket);
  321 + releaseLastSocket();
283 322 }
284 323
285 324 @Override
286 325 public void run() {
287 326 super.run();
288   - Socket socket = mWeakSocket.get();
289   - if (null != socket) {
290   - try {
291   - if (!sendRegister) {
292   - LogUtils.d(TAG, "send register mes");
293   - SocketSendMsg ssm = new SocketSendMsg().contractRegisterMsg(testRoomSn);
294   - String msg = gson.toJson(ssm) + END_SYMBOL;
295   - sendMsg(msg);
296   - LogUtils.d(TAG, "" + msg);
297   - sendRegister = true;
298   - }
299   - LogUtils.d(TAG, "send register mes end");
300   - InputStream is = socket.getInputStream();
301   - byte[] buffer = new byte[1024 * 4];
302   - int length = 0;
303   - while (!socket.isClosed() && !socket.isInputShutdown()
304   - && isStart && ((length = is.read(buffer)) != -1)) {
305   - if (length > 0) {
306   - String message = new String(Arrays.copyOf(buffer,
307   - length)).trim();
  327 +// Socket socket = mSocket.get();
  328 +// if (null != socket) {
  329 +// try {
  330 + if (!sendRegister) {
  331 + LogUtils.d(TAG, "send register mes");
  332 + SocketSendMsg ssm = new SocketSendMsg().contractRegisterMsg(testRoomSn);
  333 + String msg = gson.toJson(ssm) + END_SYMBOL;
  334 + sendMsg(msg);
  335 + LogUtils.d(TAG, "" + msg);
  336 + sendRegister = true;
  337 + }
  338 + LogUtils.d(TAG, "send register mes end");
  339 +// InputStream is = socket.getInputStream();
  340 +// byte[] buffer = new byte[1024 * 4];
  341 +// int length = 0;
  342 +// while (!socket.isClosed() && !socket.isInputShutdown()
  343 +// && isStart && ((length = is.read(buffer)) != -1)) {
  344 +// if (length > 0) {
  345 +// }
  346 +// }
  347 + StringBuilder message = new StringBuilder();
  348 + while (isStart && recvMsg(message)) {
308 349 // if (!message.contains("9997")) {
309   - LogUtils.d(TAG, "recv msg:" + message);
  350 + LogUtils.d(TAG, "recv msg:" + message);
310 351 // } else {
311 352 // LogUtils.d(TAG, "heat beat success");
312 353 // }
313   - try {
314   - if (message.endsWith(END_SYMBOL)) {
315   - message = message.replace(END_SYMBOL, "");
  354 + try {
  355 + SocketResponse socketResponse = gson.fromJson(message.toString(),
  356 + SocketResponse.class);
  357 + switch (socketResponse.getCode()) {
  358 + case SUCCESS_MESSAGE:
  359 + Log.d(TAG, "SUCCESS_MESSAGE");
  360 + break;
  361 + case VERIFY_SUCCESS:
  362 + LogUtils.d(TAG, "VERIFY_SUCCESS");
  363 + mHandler.post(heartBeatRunnable);
  364 + LogUtils.d(TAG, "verify success start heart beat");
  365 + break;
  366 + case HEART_BEAT_SUCCESS:
  367 + //每成功5次心跳判定是否启动main activity
  368 + if (++mainChargeCount == 5) {
  369 + mainChargeCount = 0;
  370 + if (ActivityCollector.getActivity(MainActivity.class) == null) {
  371 + LogUtils.d(TAG, "charge start main activity");
  372 + mHandler.postDelayed(startMainRunnable, 3 * 1000);
  373 + }
316 374 }
317   - SocketResponse socketResponse = gson.fromJson(message, SocketResponse.class);
318   - switch (socketResponse.getCode()) {
319   - case SUCCESS_MESSAGE:
320   - Log.d(TAG, "SUCCESS_MESSAGE");
321   - break;
322   - case VERIFY_SUCCESS:
323   - LogUtils.d(TAG, "VERIFY_SUCCESS");
324   - mHandler.post(heartBeatRunnable);
325   - LogUtils.d(TAG, "verify success start heart beat");
326   - break;
327   - case HEART_BEAT_SUCCESS:
328   - //每成功5次心跳判定是否启动main activity
329   - if (++mainChargeCount == 5) {
330   - mainChargeCount = 0;
331   - if (ActivityCollector.getActivity(MainActivity.class) == null) {
332   - LogUtils.d(TAG, "charge start main activity");
333   - mHandler.postDelayed(startMainRunnable, 3 * 1000);
334   - }
335   - }
336   - boolean serviceLaunched = ActivityCollector.getActivity(MainActivity.class) != null;
337   - Log.d(TAG, "HEART_BEAT_SUCCESS,MainActivity Launched:" + serviceLaunched);
338   - break;
339   - case HEART_BEAT_ERROR_SYMBOL:
340   - case ROOM_SN_CONNECTED:
341   - String msg1 = socketResponse.getCode() == HEART_BEAT_ERROR_SYMBOL ? "HEART_BEAT_ERROR_SYMBOL" : "ROOM_SN_CONNECTED";
342   - LogUtils.d(TAG, msg1);
343   - mHandler.removeCallbacks(heartBeatRunnable);
344   - mReadThread.release();
345   - sendRegister = false;
346   - releaseLastSocket(mSocket);
347   - LogUtils.d(TAG, msg1 + " before:" + +System.currentTimeMillis());
348   - try {
349   - Thread.sleep(10 * 1000);
350   - } catch (InterruptedException e) {
351   - e.printStackTrace();
352   - }
353   - LogUtils.d(TAG, msg1 + " after:" + System.currentTimeMillis());
354   - new InitSocketThread().start();
355   - break;
356   - case RETURN_VERIFY_CODE:
357   - LogUtils.d(TAG, "RETURN_VERIFY_CODE");
358   - if (!TextUtils.isEmpty(socketResponse.getData().getVerify())) {
359   - String verifyMsg = AuthCode.getDecodeStr(socketResponse.getData().getVerify());
360   - SocketSendMsg ssm = new SocketSendMsg().contractVerifyMsg(testRoomSn, verifyMsg);
361   - String msg = gson.toJson(ssm) + END_SYMBOL;
362   - sendMsg(msg);
363   - }
364   - break;
365   - case CONTAIN_MESSAGE:
366   - LogUtils.d(TAG, "CONTAIN_MESSAGE");
367   - if (socketResponse.getData() != null) {
368   - if (socketResponse.getCmd() == OPEN_DOOR) {
369   - switch (socketResponse.getData().getUser()) {
370   - //10用户,20管理员,默认值为0
371   - case 10:
372   - new SystemUtils().openFtLed(context.getApplicationContext());
373   - if (TextUtils.isEmpty(((FangTangApplication) getApplication()).getCurrentPlayUrl())) {
374   - LightOperationUtils.open();
375   - LightOperationUtils.setLightValue(Utils.getInt(context, "brightness", 50));
376   - }
377   - sendMessage(QrCodeShowActivity.KILL_SELF, "finish the QR CODE activity when new user come in");
378   - if (socketResponse.getData().getFirst() == 1) {
379   - sendMessage(USER_OPEN_DOOR_AND_GET_MOVIE, "user first open the door");
380   - } else {
381   - sendMessage(USER_OPEN_DOOR, "user open the door");
382   - }
383   - break;
384   - case 20:
385   - if (TextUtils.isEmpty(((FangTangApplication) getApplication()).getCurrentPlayUrl())) {
386   - LogUtils.d("LightOperationUtils", "admin open light");
387   - LightOperationUtils.open();
388   - LightOperationUtils.setLightValue(Utils.getInt(context, "brightness", 50));
389   - }
390   - sendMessage(JUST_OPEN_DOOR, "administrator open the door");
391   - break;
392   - case 0:
393   - sendMessage(JUST_OPEN_DOOR, "get zero none user or administrator open the door");
394   - break;
395   - default:
396   - sendMessage(JUST_OPEN_DOOR, "none user or administrator open the door");
397   - break;
398   - }
399   - } else if (socketResponse.getCmd() == CLEAN_OVER) {
400   - LogUtils.d("LightOperationUtils", "admin clean over close light");
401   - LightOperationUtils.setLightValue(5);
402   - LightOperationUtils.close();
403   - new SystemUtils().closeFtLed(context.getApplicationContext());
404   - sendMessage(QrCodeShowActivity.KILL_SELF, "finish the QR CODE activity when clean over");
405   - if (ActivityCollector.isActivityExist(SimpleAdsPlayer2.class)) {
406   - ActivityCollector.getActivity(SimpleAdsPlayer2.class).finish();
407   - }
408   - if (ActivityCollector.isActivityExist(AdsPreVideoPlayerActivity.class)) {
409   - ActivityCollector.getActivity(AdsPreVideoPlayerActivity.class).finish();
  375 + boolean serviceLaunched = ActivityCollector.getActivity(MainActivity.class) != null;
  376 + Log.d(TAG, "HEART_BEAT_SUCCESS,MainActivity Launched:" + serviceLaunched);
  377 + break;
  378 + case HEART_BEAT_ERROR_SYMBOL:
  379 + case ROOM_SN_CONNECTED:
  380 + String msg1 = socketResponse.getCode() == HEART_BEAT_ERROR_SYMBOL ? "HEART_BEAT_ERROR_SYMBOL" : "ROOM_SN_CONNECTED";
  381 + LogUtils.d(TAG, msg1);
  382 + mHandler.removeCallbacks(heartBeatRunnable);
  383 + mReadThread.release();
  384 + sendRegister = false;
  385 + releaseLastSocket();
  386 + LogUtils.d(TAG, msg1 + " before:" + +System.currentTimeMillis());
  387 + try {
  388 + Thread.sleep(10 * 1000);
  389 + } catch (InterruptedException e) {
  390 + e.printStackTrace();
  391 + }
  392 + LogUtils.d(TAG, msg1 + " after:" + System.currentTimeMillis());
  393 + new InitSocketThread().start();
  394 + break;
  395 + case RETURN_VERIFY_CODE:
  396 + LogUtils.d(TAG, "RETURN_VERIFY_CODE");
  397 + if (!TextUtils.isEmpty(socketResponse.getData().getVerify())) {
  398 + String verifyMsg = AuthCode.getDecodeStr(socketResponse.getData().getVerify());
  399 + SocketSendMsg ssm = new SocketSendMsg().contractVerifyMsg(testRoomSn, verifyMsg);
  400 + String msg = gson.toJson(ssm) + END_SYMBOL;
  401 + sendMsg(msg);
  402 + }
  403 + break;
  404 + case CONTAIN_MESSAGE:
  405 + LogUtils.d(TAG, "CONTAIN_MESSAGE");
  406 + if (socketResponse.getData() != null) {
  407 + if (socketResponse.getCmd() == OPEN_DOOR) {
  408 + switch (socketResponse.getData().getUser()) {
  409 + //10用户,20管理员,默认值为0
  410 + case 10:
  411 + new SystemUtils().openFtLed(context.getApplicationContext());
  412 + if (TextUtils.isEmpty(((FangTangApplication) getApplication()).getCurrentPlayUrl())) {
  413 + LightOperationUtils.open();
  414 + LightOperationUtils.setLightValue(Utils.getInt(context, "brightness", 50));
410 415 }
411   - if (ActivityCollector.isActivityExist(QrCodeShowActivity.class)) {
412   - ActivityCollector.getActivity(QrCodeShowActivity.class).finish();
  416 + sendMessage(QrCodeShowActivity.KILL_SELF, "finish the QR CODE activity when new user come in");
  417 + if (socketResponse.getData().getFirst() == 1) {
  418 + sendMessage(USER_OPEN_DOOR_AND_GET_MOVIE, "user first open the door");
  419 + } else {
  420 + sendMessage(USER_OPEN_DOOR, "user open the door");
413 421 }
414   - try {
415   - PollingUtils.stopPollingService(context, CountService.class, CountService.STATUS_ACTION);
416   - } catch (Exception e) {
417   - e.printStackTrace();
  422 + break;
  423 + case 20:
  424 + if (TextUtils.isEmpty(((FangTangApplication) getApplication()).getCurrentPlayUrl())) {
  425 + LogUtils.d("LightOperationUtils", "admin open light");
  426 + LightOperationUtils.open();
  427 + LightOperationUtils.setLightValue(Utils.getInt(context, "brightness", 50));
418 428 }
419   - }
  429 + sendMessage(JUST_OPEN_DOOR, "administrator open the door");
  430 + break;
  431 + case 0:
  432 + sendMessage(JUST_OPEN_DOOR, "get zero none user or administrator open the door");
  433 + break;
  434 + default:
  435 + sendMessage(JUST_OPEN_DOOR, "none user or administrator open the door");
  436 + break;
  437 + }
  438 + } else if (socketResponse.getCmd() == CLEAN_OVER) {
  439 + LogUtils.d("LightOperationUtils", "admin clean over close light");
  440 + LightOperationUtils.setLightValue(5);
  441 + LightOperationUtils.close();
  442 + new SystemUtils().closeFtLed(context.getApplicationContext());
  443 + sendMessage(QrCodeShowActivity.KILL_SELF, "finish the QR CODE activity when clean over");
  444 + if (ActivityCollector.isActivityExist(SimpleAdsPlayer2.class)) {
  445 + ActivityCollector.getActivity(SimpleAdsPlayer2.class).finish();
420 446 }
421   - break;
422   - default:
423   - LogUtils.d(TAG, "default msg:" + socketResponse.toString());
  447 + if (ActivityCollector.isActivityExist(AdsPreVideoPlayerActivity.class)) {
  448 + ActivityCollector.getActivity(AdsPreVideoPlayerActivity.class).finish();
  449 + }
  450 + if (ActivityCollector.isActivityExist(QrCodeShowActivity.class)) {
  451 + ActivityCollector.getActivity(QrCodeShowActivity.class).finish();
  452 + }
  453 + try {
  454 + PollingUtils.stopPollingService(context, CountService.class, CountService.STATUS_ACTION);
  455 + } catch (Exception e) {
  456 + e.printStackTrace();
  457 + }
  458 + }
424 459 }
425   - } catch (JsonSyntaxException e) {
426   - LogUtils.d(TAG, "error" + message + e.getMessage());
427   - e.printStackTrace();
428   - }
  460 + break;
  461 + default:
  462 + LogUtils.d(TAG, "default msg:" + socketResponse.toString());
429 463 }
  464 + } catch (JsonSyntaxException e) {
  465 + LogUtils.d(TAG, "error" + message + e.getMessage());
  466 + e.printStackTrace();
430 467 }
431   - } catch (IOException e) {
432   - LogUtils.d(TAG, "error" + e.getCause());
433   - e.printStackTrace();
  468 + LogUtils.d(TAG, "recv msg:" + message);
434 469 }
435   - }
  470 +// }
  471 +// catch (IOException e) {
  472 +// LogUtils.d(TAG, "error" + e.getCause());
  473 +// e.printStackTrace();
  474 +// }
  475 +// }
436 476 }
437 477 }
438 478
... ... @@ -443,8 +483,6 @@ public class SocketService1 extends BaseService {
443 483 EventBus.getDefault().post(messageEvent);
444 484 }
445 485
446   - boolean sendRegister = false;
447   -
448 486 @Override
449 487 public void onDestroy() {
450 488 // LogUtils.d("BaseService1", this.getClass().toString() + "");
... ...
Please register or login to post a comment