/
MySocketIOServer.java
599 lines (501 loc) · 22.5 KB
/
MySocketIOServer.java
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
package com.ufo.NettySocketioServer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import com.corundumstudio.socketio.AckCallback;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.DataListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.google.gson.Gson;
import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsService;
import com.notnoop.apns.ApnsServiceBuilder;
import com.notnoop.apns.PayloadBuilder;
import com.ufo.NettySocketioServer.Dao.UserInfoDao;
import com.ufo.NettySocketioServer.Models.DeviceTypeEnum;
import com.ufo.NettySocketioServer.Models.Message;
import com.ufo.NettySocketioServer.Models.MessageTypeEnum;
import com.ufo.NettySocketioServer.Models.Notify;
import com.ufo.NettySocketioServer.Models.Response;
import com.ufo.NettySocketioServer.Models.UserInfo;
import com.ufo.NettySocketioServer.Models.UserInfoBean;
public class MySocketIOServer extends SocketIOServer {
private RedissonClient mRedisson;
private ApnsService mApnsService;
private String mServerToken;
public MySocketIOServer(Configuration configuration) {
super(configuration);
}
public MySocketIOServer(Configuration configuration, RedissonClient redisson) {
super(configuration);
mRedisson = redisson;
}
public void setUp(String path, String password, Boolean isproduction) {
ApnsServiceBuilder builder = APNS.newService().withCert(path, password);
if (isproduction) {
mApnsService = builder.withProductionDestination().build();
} else {
mApnsService = builder.withSandboxDestination().build();
}
mServerToken = UUID.randomUUID().toString();
setUpLisenter();
setUpTopic();
}
private void setUpLisenter() {
// 登录
this.addEventListener(EventLisenter.LOGIN, String.class, new DataListener<String>() {
@Override
public void onData(SocketIOClient client, String data, AckRequest ackSender) {
Gson gson = new Gson();
UserInfo userInfo = gson.fromJson(data, UserInfo.class);
UserInfoDao userInfoDao = new UserInfoDao(mRedisson, userInfo.getSID());
List<UserInfoBean> userInfoBeans = userInfoDao.getUserInfoBeanList();
// 检查是否存在其它设备登录
if (userInfo.getCheckStatus()) {
UserInfoBean loginedUserInfoBean = getLoginedUserInfoBean(userInfoBeans, userInfo.getDeviceType(), userInfo.getDeviceToken());
if (loginedUserInfoBean != null) {
if (ackSender.isAckRequested()) {
Response response = new Response();
response.setIsSuccess(false);
String msg = String.format("您的账号于%s在一台%s设备上登录",
dateStringFromLong(loginedUserInfoBean.getLoginTime()),
loginedUserInfoBean.getDeviceType());
response.setMessage(msg);
ackSender.sendAckData(gson.toJson(response));
System.out.println(String.format("username:%s with %s has login!", userInfo.getUserName(),
userInfo.getDeviceType()));
return;
}
}
}
UserInfoBean userInfoBean = UserInfoBean.translateFromUserInfo(userInfo,
client.getSessionId().toString(), mServerToken);
userInfoDao.save(userInfoBean);
// 踢掉其它人
kickOffOthers(userInfoBeans, userInfo);
client.set("SID", userInfo.getSID());
client.set("DeviceToken", userInfo.getDeviceToken());
client.set("DeviceType", userInfo.getDeviceType());
if (ackSender.isAckRequested()) {
Response response = new Response();
response.setIsSuccess(true);
response.setMessage("登录成功");
ackSender.sendAckData(gson.toJson(response));
System.out.println(String.format("username:%s with %s login success!", userInfo.getUserName(),
userInfo.getDeviceType()));
}
}
});
// 登出
this.addEventListener(EventLisenter.LOGOFF, String.class, new DataListener<String>() {
@Override
public void onData(SocketIOClient client, String data, AckRequest ackSender) throws Exception {
// SDown 主动下线
client.set("Down", "SDown");
Gson gson = new Gson();
UserInfo userInfo = gson.fromJson(data, UserInfo.class);
if (ackSender.isAckRequested()) {
ackSender.sendAckData(gson.toJson(userInfo));
System.out.println(String.format("username:%s with %s logoff success!", userInfo.getUserName(),
userInfo.getDeviceType()));
}
client.disconnect();
}
});
// 来自同一用户在不同平台下发来的通知
this.addEventListener(EventLisenter.NOTIFYOTHERPLATFORMS, String.class, new DataListener<String>() {
@Override
public void onData(SocketIOClient client, String data, AckRequest ackSender) throws Exception {
mRedisson.getTopic(Topic.NOTIFYOTHERPLATFORMS).publish(data);
}
});
// 消息
this.addEventListener(EventLisenter.NEWS, String.class, new DataListener<String>() {
@Override
public void onData(SocketIOClient client, String data, AckRequest ackSender) throws Exception {
mRedisson.getTopic(Topic.NEWS).publish(data);
}
});
// 断线
this.addDisconnectListener(new DisconnectListener() {
@Override
public void onDisconnect(SocketIOClient client) {
String sid = client.get("SID");
String deviceToken = client.get("DeviceToken");
String down = client.get("Down");
System.out
.println(String.format("userID %s deviceToken %s disconnect down %s", sid, deviceToken, down));
UserInfoDao userInfoDao = new UserInfoDao(mRedisson, sid);
UserInfoBean userInfoBean = userInfoDao.getUserInfoBean(deviceToken);
if (userInfoBean != null) {
// 用户下线,清空用户数据
if (down != null) {
userInfoDao.del(deviceToken);
}
// 用户切换到后台,断开socket连接
else {
userInfoBean.setIsSocketConnected(false);
userInfoDao.save(userInfoBean);
}
}
mRedisson.getMap(client.getSessionId().toString()).delete();
client.disconnect();
}
});
}
private void setUpTopic() {
// 被踢下线
RTopic<String> kickoffTopic = mRedisson.getTopic(Topic.KICKOFF);
kickoffTopic.addListener(new MessageListener<String>() {
@Override
public void onMessage(String channel, String sessionID) {
SocketIOClient kickoffClient = getClient(UUID.fromString(sessionID));
if (kickoffClient != null) {
String sid = kickoffClient.get("SID");
String deviceType = kickoffClient.get("DeviceType");
String deviceToken = kickoffClient.get("DeviceToken");
UserInfoDao userInfoDao = new UserInfoDao(mRedisson, sid);
UserInfoBean loginedUserInfoBean = getLoginedUserInfoBean(userInfoDao.getUserInfoBeanList(),
deviceType, deviceToken);
Response response = new Response();
response.setIsSuccess(true);
if (loginedUserInfoBean != null) {
String msg = String.format("您的账号于%s在一台%s设备上登录",
dateStringFromLong(loginedUserInfoBean.getLoginTime()),
loginedUserInfoBean.getDeviceType());
response.setMessage(msg);
}
Gson gson = new Gson();
String json = gson.toJson(response);
kickoffClient.sendEvent(Event.KICKOFF, json);
// KDown 被踢下线
kickoffClient.set("Down", "KDown");
kickoffClient.disconnect();
System.out.println(String.format("SessionID:%s was kicked off", sessionID));
}
}
});
// 消息
RTopic<String> newsTopic = mRedisson.getTopic(Topic.NEWS);
newsTopic.addListener(new MessageListener<String>() {
@Override
public void onMessage(String channel, String data) {
Gson gson = new Gson();
Message message = gson.fromJson(data, Message.class);
Message messageForSend = gson.fromJson(data, Message.class);
for (String receiverID : message.getReceiverIDs()) {
sendNews(receiverID, messageForSend);
}
// 发送给自己的其它平台
UserInfoDao userInfoDao = new UserInfoDao(mRedisson, message.getSenderID());
List<UserInfoBean> userInfoBeans = userInfoDao.getUserInfoBeanList();
for (UserInfoBean userInfoBean : userInfoBeans) {
if (!userInfoBean.getDeviceToken().equals(message.getSenderDeviceToken())) {
SocketIOClient client = getClient(UUID.fromString(userInfoBean.getSessionID()));
if (client != null) {
client.sendEvent(Event.NEWS, new AckCallback<String>(String.class) {
@Override
public void onSuccess(String result) {
System.out.println(String.format("UserID %s on %s reply %s!",
userInfoBean.getUserID(), userInfoBean.getDeviceType(), result));
}
}, data);
}
}
}
}
});
// 广播
RTopic<String> broadcastTopic = mRedisson.getTopic(Topic.BROADCAST);
broadcastTopic.addListener(new MessageListener<String>() {
@Override
public void onMessage(String channel, String data) {
getBroadcastOperations().sendEvent(Event.BROADCAST, data);
}
});
// 通知当前用户的不同设备
RTopic<String> notifyTopic = mRedisson.getTopic(Topic.NOTIFYOTHERPLATFORMS);
notifyTopic.addListener(new MessageListener<String>() {
@Override
public void onMessage(String channel, String data) {
Gson gson = new Gson();
Notify notify = gson.fromJson(data, Notify.class);
UserInfoDao userInfoDao = new UserInfoDao(mRedisson, notify.getUserID());
List<UserInfoBean> userInfoBeans = userInfoDao.getUserInfoBeanList();
for (UserInfoBean userInfoBean : userInfoBeans) {
if (!notify.getSourceDeviceType().equals(userInfoBean.getDeviceType())) {
SocketIOClient client = getClient(UUID.fromString(userInfoBean.getSessionID()));
if (client != null) {
client.sendEvent(Event.NOTIFYOTHERPLATFORMS, data);
System.out.println(String.format("userID:%s notify from %s to %s", notify.getUserID(),
notify.getSourceDeviceType(), userInfoBean.getDeviceType()));
}
}
}
}
});
}
/**
* 检查其它设备登录情况
*
* @param userInfoBeans
* @param deviceType
* @param deviceToken
* @return
*/
private UserInfoBean getLoginedUserInfoBean(List<UserInfoBean> userInfoBeans, String deviceType, String deviceToken) {
if (deviceType.equals(DeviceTypeEnum.PC)) {
for (UserInfoBean userInfoBean : userInfoBeans) {
if (userInfoBean.getDeviceType().equals(DeviceTypeEnum.PC)
&& !userInfoBean.getDeviceToken().equals(deviceToken)) {
return userInfoBean;
}
}
} else {
for (UserInfoBean userInfoBean : userInfoBeans) {
if ((userInfoBean.getDeviceType().equals(DeviceTypeEnum.ANDROID)
|| userInfoBean.getDeviceType().equals(DeviceTypeEnum.IOS))
&& !userInfoBean.getDeviceToken().equals(deviceToken)) {
return userInfoBean;
}
}
}
return null;
}
/**
* 检查并踢掉相同平台下已登陆用户
*
* @param userInfoBeans
* @param loginUser
* @return
*/
private boolean kickOffOthers(List<UserInfoBean> userInfoBeans, UserInfo loginUser) {
UserInfoDao userInfoDao = new UserInfoDao(mRedisson, loginUser.getSID());
for (UserInfoBean userInfoBean : userInfoBeans) {
//PC踢PC
if (loginUser.getDeviceType().equals(DeviceTypeEnum.PC)
&& userInfoBean.getDeviceType().equals(DeviceTypeEnum.PC)
&& !userInfoBean.getDeviceToken().equals(loginUser.getDeviceToken())) {
if (userInfoBean.getIsSocketConnected()) {
mRedisson.getTopic(Topic.KICKOFF).publish(userInfoBean.getSessionID());
} else {
userInfoDao.del(userInfoBean.getDeviceToken());
}
return true;
}
//移动踢移动
if (!loginUser.getDeviceType().equals(DeviceTypeEnum.PC)
&& !userInfoBean.getDeviceType().equals(DeviceTypeEnum.PC)
&& !userInfoBean.getDeviceToken().equals(loginUser.getDeviceToken())) {
if (userInfoBean.getIsSocketConnected()) {
mRedisson.getTopic(Topic.KICKOFF).publish(userInfoBean.getSessionID());
} else {
userInfoDao.del(userInfoBean.getDeviceToken());
}
return true;
}
}
return false;
}
/**
* 发送消息
*
* @param receiverID
* @param msg
*/
private void sendNews(String receiverID, Message msg) {
UserInfoDao userInfoDao = new UserInfoDao(mRedisson, receiverID);
List<UserInfoBean> userInfoBeans = userInfoDao.getUserInfoBeanList();
for (UserInfoBean userInfoBean : userInfoBeans) {
// 非IOS或IOS前台在线
if (!userInfoBean.getDeviceType().equals(DeviceTypeEnum.IOS)
|| (userInfoBean.getDeviceType().equals(DeviceTypeEnum.IOS)
&& userInfoBean.getIsSocketConnected())) {
SocketIOClient client = getClient(UUID.fromString(userInfoBean.getSessionID()));
if (client == null)
continue;
System.out.println(
String.format("UserID %s send %s to %s", msg.getSenderID(), msg.getBody(), receiverID));
HashSet<String> hashSet = new HashSet<>();
hashSet.add(receiverID);
msg.setReceiverIDs(hashSet);
Gson gson = new Gson();
String data = gson.toJson(msg);
client.sendEvent(Event.NEWS, new AckCallback<String>(String.class) {
@Override
public void onSuccess(String result) {
System.out.println(String.format("UserID %s on %s reply %s!", receiverID,
userInfoBean.getDeviceType(), result));
}
}, data);
}
// if (userInfoBean.getDeviceType().equals(DeviceTypeEnum.ANDROID))
// {
// SocketIOClient client =
// getClient(UUID.fromString(userInfoBean.getSessionID()));
// if (client == null)
// continue;
//
// System.out.println(
// String.format("UserID %s send %s to %s", msg.getSenderID(),
// msg.getBody(), receiverID));
//
// HashSet<String> hashSet = new HashSet<>();
// hashSet.add(receiverID);
// msg.setReceiverIDs(hashSet);
//
// Gson gson = new Gson();
// String data = gson.toJson(msg);
//
// client.sendEvent(Event.NEWS, new
// AckCallback<String>(String.class) {
// @Override
// public void onSuccess(String result) {
// System.out.println(String.format("UserID %s on Android reply
// %s!", receiverID, result));
// }
// }, data);
// } else if
// (userInfoBean.getDeviceType().equals(DeviceTypeEnum.IOS)) {
// SocketIOClient client =
// getClient(UUID.fromString(userInfoBean.getSessionID()));
//
// if (client == null)
// continue;
//
// System.out.println(
// String.format("UserID %s send %s to %s", msg.getSenderID(),
// msg.getBody(), receiverID));
//
// HashSet<String> hashSet = new HashSet<>();
// hashSet.add(receiverID);
// msg.setReceiverIDs(hashSet);
//
// Gson gson = new Gson();
// String data = gson.toJson(msg);
//
// client.sendEvent(Event.NEWS, new
// AckCallback<String>(String.class) {
// @Override
// public void onSuccess(String result) {
// System.out.println(String.format("UserID %s on IOS reply %s!",
// receiverID, result));
// }
// }, data);
//
// } else {
// SocketIOClient client =
// getClient(UUID.fromString(userInfoBean.getSessionID()));
// if (client == null)
// continue;
//
// System.out.println(
// String.format("UserID %s send %s to %s", msg.getSenderID(),
// msg.getBody(), receiverID));
//
// HashSet<String> hashSet = new HashSet<>();
// hashSet.add(receiverID);
// msg.setReceiverIDs(hashSet);
//
// Gson gson = new Gson();
// String data = gson.toJson(msg);
//
// client.sendEvent(Event.NEWS, new
// AckCallback<String>(String.class) {
// @Override
// public void onSuccess(String result) {
// System.out.println(String.format("UserID %s on PC reply %s!",
// receiverID, result));
// }
// }, data);
// }
}
// IOS后台在线且最后一次登录是在该服务器上
UserInfoBean iosUserInfoBean = IOSInbackground(receiverID);
if (iosUserInfoBean != null && iosUserInfoBean.getServerToken().equals(mServerToken)) {
int badge = iosUserInfoBean.getUnReadCount();
badge++;
iosUserInfoBean.setUnReadCount(badge);
userInfoDao.save(iosUserInfoBean);
sendToAPN(msg, iosUserInfoBean.getDeviceToken(), badge);
}
}
/**
* APNS推送
*
* @param msg
* @param deviceToken
*/
private void sendToAPN(Message msg, String deviceToken, int badge) {
if (!msg.getIsAlert())
return;
PayloadBuilder builder = APNS.newPayload().badge(badge).alertTitle(msg.getTitle())
.customField("othersType", msg.getOthersType()).customField("others", msg.getOthers())
.category(msg.getCategory()).mutableContent();
switch (msg.getMessageType()) {
case MessageTypeEnum.TEXT:
builder.alertBody(msg.getBody());
break;
case MessageTypeEnum.IMAGE:
builder.alertBody("[图片]");
break;
case MessageTypeEnum.FILE:
builder.alertBody("[文件]");
break;
case MessageTypeEnum.URL:
builder.alertBody("[链接]");
break;
case MessageTypeEnum.SOUND:
builder.alertBody("[音频]");
break;
case MessageTypeEnum.MOVIE:
builder.alertBody("[视频]");
break;
case MessageTypeEnum.EMOJI:
builder.alertBody("[表情]");
break;
default:
break;
}
String payload = builder.build();
mApnsService.push(deviceToken, payload);
}
/**
* ios后台在线
*
* @param userID
* @return
*/
private UserInfoBean IOSInbackground(String userID) {
UserInfoDao userInfoDao = new UserInfoDao(mRedisson, userID);
List<UserInfoBean> userInfoBeans = userInfoDao.getUserInfoBeanList();
for (UserInfoBean userInfoBean : userInfoBeans) {
if (userInfoBean.getDeviceType().equals(DeviceTypeEnum.IOS) && !userInfoBean.getIsSocketConnected()) {
return userInfoBean;
}
}
return null;
}
private String dateStringFromLong(long date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(new Date(date));
}
/**
* 守护线程
*/
// private class DaemonThreadFactory implements ThreadFactory {
// public Thread newThread(Runnable r) {
// Thread t = new Thread(r);
// t.setDaemon(true);
// return t;
// }
// }
}