18ca6348d68857751be79faff0c79591dea4088a.svn-base
2.0 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
package com.espeed.socket;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.espeed.socket.EchoServlet.WebSocketMessageInbound;
public class WebSocketMessageInboundPool {
//保存连接的MAP容器
private static final Map<String,WebSocketMessageInbound> connections = new HashMap<String,WebSocketMessageInbound>();
//向连接池中添加连接
public static void addMessageInbound(WebSocketMessageInbound inbound){
//添加连接
connections.put(inbound.getUserid(),inbound);
}
//获取所有的在线用户
public static Set<String> getOnlineUser(){
return connections.keySet();
}
public static void removeMessageInbound(WebSocketMessageInbound inbound){
System.out.println("移除连接");
//移除连接
connections.remove(inbound.getUserid());
}
public static void sendMessageToUser(String userid,String message){
try {
//向特定的用户发送数据
WebSocketMessageInbound inbound = connections.get(userid);
if(inbound != null){
inbound.getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
}
} catch (IOException e) {
e.printStackTrace();
}
}
//向所有的用户发送消息
public static void sendMessage(String message){
try {
Set<String> keySet = connections.keySet();
for (String key : keySet) {
WebSocketMessageInbound inbound = connections.get(key);
if(inbound != null){
System.out.println("send message to user : " + key + " ,message content : " + message);
inbound.getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}