WebSocket主动向前端推送消息,避免造成资源浪费。记录下简单使用过程,方便以后使用
java代码
新建WebConfig类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
新建WebSocketService
@ServerEndpoint("/webSocket/{sid}")
@Component
public class WebSocketServer {
//静态是变量,用于记录当前连接数,应该把它设计成线程安全的
private static AtomicInteger onlineNum = new AtomicInteger();
//concurrent包的线程安全set,用来存放每个客户端对应的WebSocketServer对象
private static ConcurrentHashMap<String , Session>sessionPools = new ConcurrentHashMap<>();
//发送消息
public void sendMessage(Session session, String message) throws IOException {
if(session != null){
synchronized (session) {
// System.out.println("发送数据:" + message);
session.getBasicRemote().sendText(message);
}
}
}
//给指定用户发送信息
public void sendInfo(String userName, String message){
Session session = sessionPools.get(userName);
try {
sendMessage(session, message);
}catch (Exception e){
e.printStackTrace();
}
}
//建立连接成功调用
@OnOpen
public void onOpen(Session session, @PathParam(value = "sid") String userName){
sessionPools.put(userName, session);
addOnlineCount();
System.out.println(userName + "加入webSocket!当前人数为" + onlineNum);
}
//关闭连接时调用
@OnClose
public void onClose(@PathParam(value = "sid") String userName){
sessionPools.remove(userName);
subOnlineCount();
System.out.println(userName + "断开webSocket连接!当前人数为" + onlineNum);
}
//收到客户端信息
@OnMessage
public void onMessage(String message) throws IOException{
message = "客户端:" + message + ",已收到";
System.out.println(message);
for (Session session: sessionPools.values()) {
try {
sendMessage(session, message);
} catch(Exception e){
e.printStackTrace();
continue;
}
}
}
//错误时调用
@OnError
public void onError(Session session, Throwable throwable){
System.out.println("发生错误");
throwable.printStackTrace();
}
public static void addOnlineCount(){
onlineNum.incrementAndGet();
}
public static void subOnlineCount() {
onlineNum.decrementAndGet();
}
}
推送消息逻辑可自己实现
定时任务或redis更新数据时直接向前端推送消息
定时任务
@Async
@Scheduled(cron = "0/5 * * * * ?")
public void Run() {
//具体业务逻辑实现
{
#######
}
//发送消息给admin
webSocketServer.sendInfo("admin", "[" + str + "]");
}
Controller代码(非常简单)
@Controller
public class SocketController {
@Autowired
private WebSocketServer webSocketServer;
@RequestMapping("/index")
public String socketIndex(){
return "index";
}
@GetMapping("/webSocket")
public ModelAndView socket(){
ModelAndView mav = new ModelAndView("front/webSocket");
return mav;
}
}
前端JS代码
<script>
var socket;
function openSocket() {
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
var userId = document.getElementById('userId').value;
// var socketUrl="ws://127.0.0.1:22599/webSocket/"+userId;
var socketUrl = "ws://127.0.0.1:8000/webSocket/" + userId;
console.log(socketUrl);
if (socket != null) {
socket.close();
socket = null;
}
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function () {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
/* var serverMsg = "收到服务端信息:" + msg.data;
console.log(serverMsg);*/
loadDataToView(JSON.parse(msg.data));
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function () {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function () {
console.log("websocket发生了错误");
}
}
}
function sendMessage() {
if (typeof (WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
// console.log("您的浏览器支持WebSocket");
var toUserId = document.getElementById('toUserId').value;
var contentText = document.getElementById('contentText').value;
var msg = '{"toUserId":"' + toUserId + '","contentText":"' + contentText + '"}';
console.log(msg);
socket.send(msg);
}
}
</script>
JS获取admin用户,发送消息时可指定用户发送
<div><input id="userId" name="userId" type="hidden" value="admin"></div>