开发中经常会有这样的使用场景.如某个用户在一个数据上做了xx操作, 与该数据相关的用户在线上的话,需要实时接收到一条信息.
这种可以使用WebSocket来实现. 另外,对于消息,可以定义一个类进行固化. 主要是消息内容,接收人,发送人,是否已发送等. 用户上线时, 通过方法去查询出来然后进行发送
@ServerEndpoint(value = "/websocket/{sessionId}") public class MyWebSocket { //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static AtomicInteger onlineCount = new AtomicInteger(0); //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 public static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 public Session session; /** * 连接建立成功调用的方法 * * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(Session session) { this.session = session; if (webSocketSet.add(this)) { System.out.println("有新连接加入!当前在线人数为" + onlineCount.incrementAndGet()); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { if (webSocketSet.remove(this)) { System.out.println("有一连接关闭!当前在线人数为" + onlineCount.decrementAndGet()); } } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息 * @param session 可选的参数 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("来自客户端的消息:" + message); //群发消息 /* for(MyWebSocket item: webSocketSet){ try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue; } }*/ } /** * 发生错误时调用 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.out.println("发生错误"); error.printStackTrace(); } private static ReentrantLock lock = new ReentrantLock(true); /** * 该方法是我们根据业务需要调用的. * * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { synchronized(this.session) { if (session.isOpen()) { this.session.getAsyncRemote().sendText(message); } } } }
页面中的调用.每个客户都要初始化一个websocket示例. 其中我们用用户的userId作为标识的一部分.
//页面加载完成. 初始化一个webSocket对象.然后可以根据需要调一个来发信息 window.onload = function () { initWebSocket(); setTimeout(function(){ $.post('<%=basePath %>xxx.do',function(r){ //alert(0); }); },2000); }; function initWebSocket() { webSocket = new WebSocket(requestUrl.replace("http", "ws") + 'websocket/${userId}'); webSocket.onerror = function (event) { onError(event) }; //连接建立成功事件 webSocket.onopen = function (event) { onOpen(event) }; //接收到服务端消息事件 webSocket.onmessage = function (event) { onMessage(event) }; }