只讲重点,其他的可以查看我的上一篇博客,
首先定义两个全局变量:
private Session session;//该session是websocket的session
private static final Map<String,Object> connections = new HashMap<String,Object>(); //创建一个用来存所有连接过的session,这里的key我放的是userId
获取session是在websocket打开的时候,当关闭的时候,将该用户的key移除即可。
@OnOpen // 成功连接时执行此代码
public void onOpen(Session session, EndpointConfig config) {
this.session = session;
HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
fromUser = (User)httpSession.getAttribute("user");
/**
* 将连接成功的用户存入connections内
*/
connections.put(fromUser.getUserId(), session);
ac = new ClassPathXmlApplicationContext("beans.xml");
hibernateTemplate = ac.getBean("hibernateTemplate", HibernateTemplate.class);
System.out.println("------------webSocket is Open------------");
}
@OnClose // 连接关闭时执行
public void onClose() {
/**
* 当用户下线时,进行移除!
*/
connections.remove(fromUser.getUserId());
System.out.println("------------webSocket is onClose------------");
}
这样当你获取你想要推送消息的用户的websocket的session时,你就可以这样:
Session toUserSession = (Session)connections.get(toUserId);
toUserSession.getBasicRemote().sendText("我在给你推送消息啊!");
这样就可以将消息直接推送过去,被推送的用户,只需在前台的js的websocket的
webSocket.onmessage = function(event) //接受客户端消息
{
onMessage(event);//在这里可以获取到数据!
};
如果是给所有人都推送,直接遍历所有的sesion然后挨个推送即可。