可用于群发消息和推送消息给指定用户
web socket实现类
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
//configurator = WebsocketConfig.class 该属性就是我上面配置的信息
@ServerEndpoint(value = "/websocket/{userId}", configurator = WebSocketConfig.class)
@Component //此注解千万千万不要忘记,它的主要作用就是将这个监听器纳入到Spring容器中进行管理
public class WebSocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 用户ID
*/
private Integer userId;
/**
* 连接建立成功调用的方法
* <p>
* config用来获取WebsocketConfig中的配置信息
*/
@OnOpen
public void onOpen(Session session, EndpointConfig config, @PathParam("userId")Integer userId) {
//获取WebsocketConfig.java中配置的“sessionId”信息值
String httpSessionId = (String) config.getUserProperties().get("sessionId");
this.userId = userId;
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
// try {
// sendMessage("Hello world");
// } catch (IOException e) {
// System.out.println("IO异常");
// }
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//群发消息
for (WebSocket item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
/**
* 群发自定义消息
*/
public static void sendInfo(String message) throws IOException {
for (WebSocket item : webSocketSet) {
item.session.getAsyncRemote().sendText(message);//群发给所有人
// try {
// item.sendMessage(message);
// } catch (IOException e) {
// continue;
// }
}
}
/**
* 推送给指定id自定义消息
*/
public static void sendInfo(String message, Integer userId) throws IOException {
for (WebSocket item : webSocketSet) {
System.out.println("进来了吗" + item.userId + "----" + userId);
System.out.println(item.userId.equals(userId));
if(item.userId == userId || item.userId.equals(userId)){
item.session.getAsyncRemote().sendText(message);//群发给所有人
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
}
web socket配置类
import org.apache.catalina.session.StandardSessionFacade;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
@Configuration
public class WebSocketConfig extends Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
/*如果没有监听器,那么这里获取到的HttpSession是null*/
StandardSessionFacade ssf = (StandardSessionFacade) request.getHttpSession();
if (ssf != null) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
//关键操作
sec.getUserProperties().put("sessionId", httpSession.getId());
System.out.println("获取到的SessionID:" + httpSession.getId());
}
}
/**
* 引入shiro框架下的session,获取session信息
*/
/*
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
Session shiroSession = ShiroUtils.getSubjct().getSession();
sec.getUserProperties().put("sessionId", shiroSession.getId());
}
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
//这个对象说一下,貌似只有服务器是tomcat的时候才需要配置,具体我没有研究
return new ServerEndpointExporter();
}
}
//推送给指定id
WebSocket.sendInfo(jsonObject.toString(),allTodayMeetingDetails.get(i).getId());
//群发
WebSocket.sendInfo(jsonObject.toString());