功能描述
举个栗子,我们在浏览知乎等之类的网站时,如果有新内容更新了,那么在内容列表上方会弹出个小框,告诉你有新内容更新,你一点击,列表就更新。
再比如,我想实现论坛一有人发帖或者管理员改变了帖子的状态时,在论坛主页提醒用户们帖子内容有更新,可以点击按钮选择更新。
实现细节
- 关于WebSocket的原理可以看这里(建议看原文,我自己总结的太水。。。):
WebSocket的原理:WebSocket 是什么原理?为什么可以实现持久连接?
我看后总结的:WebSocket 是什么原理?为什么可以实现持久连接?(笔记)
- 向所有人广播:
WSAllController
package controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.websocket.*;
import javax.websocket.server.*;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by 阿越 on 2017/6/6.
*/
@ServerEndpoint("/wsAll")
public class WSAllController {
private static final Logger logger = LoggerFactory.getLogger(WSAllController.class);
public static Map<String, Session> clients = new ConcurrentHashMap<String, Session>();
/**
* 打开连接时触发
*
* @param session
*/
@OnOpen
public void onOpen(Session session) {
logger.info("Websocket Start Connecting:" + session.getId());
System.out.println("进入:" + session.getId());
clients.put(session.getId(), session);
}
/**
* 收到客户端消息时触发
*
* @param message
* @return
*/
@OnMessage
public String onMessage(String message) {
return "Got your message (" + message + ").Thanks !";
}
/**
* 异常时触发
*
* @param throwable
*/
@OnError
public void onError(Throwable throwable, Session session) {
logger.info("Websocket Connection Exception:" + session.getId());
logger.info(throwable.getMessage(), throwable);
clients.remove(session.getId());
}
/**
* 关闭连接时触发
*/
@OnClose
public void onClose(Session session) {
logger.info("Websocket Close Connection:" + session.getId());
clients.remove(session.getId());
}
/**
* 向所有人广播
*
* @param message
*/
public static void broadcastAll(String message) {
Set<Map.Entry<String, Session>> set = clients.entrySet();
for (Map.Entry<String, Session> i : set) {
try {
i.getValue().getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在处理业务的代码上调用broadcastAll(String message)方法
/**
* 置顶
*
* @param request
* @return
*/
@RequestMapping("/setTop")
public void setTop(...) throws IOException {
...
WebsocketController.broadcastAll("有新内容");
...
}
页面建立连接
<script type="text/javascript">
$(function () {
initSocket();
});
// ----------- webSocket begin -------------
function initSocket() {
var webSocket = null;
window.onbeforeunload = function () {
//离开页面时的其他操作
};
if (!window.WebSocket) {
console("您的浏览器不支持websocket!");
return false;
}
var target = 'ws://' + window.location.host + "/wsAll";
if ('WebSocket' in window) {
webSocket = new WebSocket(target);
} else if ('MozWebSocket' in window) {
webSocket = new MozWebSocket(target);
} else {
alert('WebSocket is not supported by this browser.');
return;
}
// 收到服务端消息
webSocket.onmessage = function (msg) {
alert(msg);
// 关闭连接
webSocket.onclose();
console.log(msg);
};
// 异常
webSocket.onerror = function (event) {
console.log(event);
};
// 建立连接
webSocket.onopen = function (event) {
console.log(event);
};
// 断线
webSocket.onclose = function () {
console.log("websocket断开连接");
};
}
// ----------- webSocket end -------------
</script>
- 向特定的客户广播:
WSOneController
package controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.websocket.*;
import javax.websocket.server.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by 阿越 on 2017/6/6.
*/
@ServerEndpoint("/wsOne/{myWebsocket}")
public class WSOneController {
private static final Logger logger = LoggerFactory.getLogger(WSOneController.class);
public static Map<String, Session> clients = new ConcurrentHashMap<String, Session>();
/**
* 打开连接时触发
*
* @param myWebsocket
* @param session
*/
@OnOpen
public void onOpen(@PathParam("myWebsocket") String myWebsocket, Session session) {
logger.info("Websocket Start Connecting:" + myWebsocket);
System.out.println("进入:" + myWebsocket);
clients.put(myWebsocket, session);
}
/**
* 收到客户端消息时触发
*
* @param message
* @return
*/
@OnMessage
public String onMessage(String message) {
return "Got your message (" + message + ").Thanks !";
}
/**
* 异常时触发
*
* @param myWebsocket
* @param throwable
*/
@OnError
public void onError(@PathParam("myWebsocket") String myWebsocket, Throwable throwable) {
logger.info("Websocket Connection Exception:" + myWebsocket);
logger.info(throwable.getMessage(), throwable);
clients.remove(myWebsocket);
}
/**
* 关闭连接时触发
*
* @param myWebsocket
*/
@OnClose
public void onClose(@PathParam("myWebsocket") String myWebsocket) {
logger.info("Websocket Close Connection:" + myWebsocket);
clients.remove(myWebsocket);
}
/**
* 异步的方式将数据传回客户端
*
* @param myWebsocket
* @param message
*/
public static void broadcast(String myWebsocket, String message) {
if (clients.containsKey(myWebsocket)) {
clients.get(myWebsocket).getAsyncRemote().sendText(message);
} else {
throw new NullPointerException("[" + myWebsocket + "]Connection does not exist");
}
}
}
在处理业务的代码上调用broadcast(String myWebsocket, String message)方法,假设此时的myWebsocket是post(帖子)
/**
* 置顶
*
* @param request
* @return
*/
@RequestMapping("/setTop")
public void setTop(...) throws IOException {
...
WebsocketController.broadcast("post","有新内容");
...
}
页面建立连接
<script type="text/javascript">
$(function () {
initSocket("post");
});
// ----------- webSocket begin -------------
function initSocket(myWebsocket) {
var webSocket = null;
window.onbeforeunload = function () {
//离开页面时的其他操作
};
if (!window.WebSocket) {
console("您的浏览器不支持websocket!");
return false;
}
var target = 'ws://' + window.location.host + "/wsAll/" + myWebsocket;
if ('WebSocket' in window) {
webSocket = new WebSocket(target);
} else if ('MozWebSocket' in window) {
webSocket = new MozWebSocket(target);
} else {
alert('WebSocket is not supported by this browser.');
return;
}
// 收到服务端消息
webSocket.onmessage = function (msg) {
alert(msg);
// 关闭连接
webSocket.onclose();
console.log(msg);
};
// 异常
webSocket.onerror = function (event) {
console.log(event);
};
// 建立连接
webSocket.onopen = function (event) {
console.log(event);
};
// 断线
webSocket.onclose = function () {
console.log("websocket断开连接");
};
}
// ----------- webSocket end -------------
</script>
结果展示
初始列表:
用户发帖或管理员修改帖子后(比如,我们把帖子“测试ayue”的加精状态去掉):
点击“有新内容”按钮,进行列表更新(注意整个网页是没刷新,只有列表这部分刷新而已):
可以看到,帖子“测试ayue”的加精状态已经去掉了。
如果觉得文章对您有用,麻烦点击关注和喜欢,感谢支持!