MyWebSocket.java
4.34 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
package com.glsx.usercenter.component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.common.constants.ResultObject;
import com.glsx.usercenter.constants.ResultCodeEnum;
/**
*
* @Title MyWebSocket.java
* @Package com.glsx.usercenter.component
* @Description TODO websocket的配置
* @author zhanghj
* @date 2019年8月16日 下午2:32:55
* @version 1.0.0
*/
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class MyWebSocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
public static ConcurrentHashMap<Integer, MyWebSocket> webSocketSet = new ConcurrentHashMap<Integer, MyWebSocket>(16);
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private static Logger log = LoggerFactory.getLogger(MyWebSocket.class);
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(@PathParam(value="userId") Integer userId,Session session) {
log.info("userId="+userId);
this.session = session;
addWebSocketSet(userId, this);
}
private void addWebSocketSet(Integer userId, MyWebSocket myWebSocket) {
// TODO Auto-generated method stub
if (webSocketSet.containsKey(userId)) {
webSocketSet.replace(userId, myWebSocket);
} else {
webSocketSet.put(userId, myWebSocket);
addOnlineCount(); //在线数加1
log.info("有新连接加入!当前在线人数为" + getOnlineCount());
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam(value="userId") Integer userId) {
webSocketSet.remove(userId); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) throws Exception {
this.session = session;
message = "来自客户端的消息:" + message;
log.info(message);
try {
JSONObject json = new JSONObject();
sendMessage( json);
} catch (Exception e) {
log.error("onMessage方法异常"+e.toString());
e.printStackTrace();
}
//群发消息
// sendInfo("群发消息"+message);
}
/**
* 发生错误时调用
@OnError
**/
public void onError(Session session, Throwable error) {
log.error("onMessage方法异常"+error.toString());
error.printStackTrace();
}
/**
* 发送消息需注意方法加锁synchronized,避免阻塞报错
* 注意session.getBasicRemote()与session.getAsyncRemote()的区别
* @param message
* @throws IOException
* @throws EncodeException
*/
public synchronized void sendMessage(JSONObject message) throws IOException, EncodeException {
//this.session.getBasicRemote().sendText(message);
ResultObject result = new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), message);
this.session.getAsyncRemote().sendText(JSON.toJSONString(result));
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}