配置
package cn.deltalpha.framework.admin.socket;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Component
public class MyWebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
方法
package cn.deltalpha.framework.admin.socket;
import org.springframework.stereotype.Component;
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 java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint("/myWebsocket/{name}")
public class MyWebSocket {
private Session session;
private String name;
private static ConcurrentHashMap<String, MyWebSocket> webSocketSet = new ConcurrentHashMap<>();
@OnOpen
public void OnOpen(Session session, @PathParam(value = "name") String name) {
this.session = session;
this.name = name;
webSocketSet.put(name, this);
System.out.println(("[WebSocket] 连接成功,当前连接人数为:={}"+ webSocketSet.size()));
}
@OnClose
public void OnClose() {
webSocketSet.remove(this.name);
System.out.println(("[WebSocket] 退出成功,当前连接人数为:={}" + webSocketSet.size()));
}
@OnMessage
public void OnMessage(String message) {
System.out.println(("[WebSocket] 收到消息:{}" + message));
if (message.indexOf("TOUSER") == 0) {
String name = message.substring(message.indexOf("TOUSER") + 6, message.indexOf(";"));
AppointSending(name, message.substring(message.indexOf(";") + 1, message.length()));
} else {
GroupSending(message);
}
}
public void GroupSending(String message) {
for (String name : webSocketSet.keySet()) {
try {
webSocketSet.get(name).session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void AppointSending(String name, String message) {
try {
webSocketSet.get(name).session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|