websocket替代定时器实时刷新

1. 在页面a.html页面定义一个websocket

var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
	websocket = new WebSocket(
		"ws://ip:端口/项目名/websocket?a");
} else {
	layer.alert('您的浏览器不支持websocket,需要手动刷新b页面!');
}

2. a.html中相应的触发位置添加

websocket.send();

3.服务端代码

@ServerEndpoint(value = "/websocket")
public class MyWebSocket {
	//a与b页面的连接会话,需要通过它来给b发送数据
	private Session session;

	/**
	 * 连接建立成功调用的方法
	 * @param session  可选的参数
	 * @throws Exception 
	 */
	@OnOpen
	public void onOpen(Session session) throws Exception {
		this.session = session;
		WebSocketMap.put(session.getQueryString(), this);
	}

	/**
	 * 连接关闭调用的方法
	 * @throws Exception 
	 */
	@OnClose
	public void onClose() throws Exception {
		//从map中删除
		WebSocketMap.remove(session.getQueryString());
	}

	/**
	 * 收到a消息后调用的方法
	 * @param message 客户端发送过来的消息
	 * @param session 可选的参数
	 * @throws IOException 
	 */
	@OnMessage
	public void onMessage(String message, Session session) throws IOException {
		try {
			this.sendMessages(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发生错误时调用
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		error.printStackTrace();
	}

	/**
	 * 发送消息方法。
	 * @param message
	 * @throws IOException
	 */
	public void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
	}

	/**
	 * 给b发消息方法。
	 * @param message
	 * @throws IOException
	 */
	public void sendMessages(String message) throws IOException {
		MyWebSocket myWebSocket = WebSocketMap.get("b");
		myWebSocket.sendMessage(message);
	}
}

4.服务端使用的Map类

public class WebSocketMap {
	public static ConcurrentMap<String, MyWebSocket> webSocketMap = new ConcurrentHashMap<>();

	public static void put(String key, MyWebSocket myWebSocket) {
		webSocketMap.put(key, myWebSocket);
	}

	public static MyWebSocket get(String key) {
		return webSocketMap.get(key);
	}

	public static void remove(String key) {
		webSocketMap.remove(key);
	}

	public static Collection<MyWebSocket> getValues() {
		return webSocketMap.values();
	}
}

5.在b.html页面中同样定义websocket

var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
	websocket = new WebSocket(
		"ws://ip:端口/项目名/websocket?b");
} else {
	layer.alert('您的浏览器不支持websocket,需要手动刷新b页面!');
}

6.接收a发送来的消息,刷新b页面

websocket.onmessage = function(event) {	};





猜你喜欢

转载自blog.csdn.net/qq_21299835/article/details/80664594