开始先提一下,我在写websocket是进入了一个误区,我要检测数据库有没有新添加的订单,有的话推送给前台,前台会进行提示,我本以为我要一直监测数据库,比如说写一个定时函数,一直查询数据库,发现有新的就返回,实际上这是不可能的,太消耗性能,既然已经建立了长连接,我们就要在添加订单是发送请求给websocket由他推送给前台(因为分工问题,添加订单不是我写的)。代码如下:
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
static Log log= LogFactory.getLog(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount();
System.out.println("session:"+session);
//在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
try {
this.session.getBasicRemote().sendText(message);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
开启websocket访问配置
/**
* 开启WebSocket支持
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
推送前台数据Controller
//推送数据接口
@CrossOrigin(value = "*")
@ResponseBody
@PostMapping("/socket/push")
public void pushToWeb(String hotelId, String message) {
try {
WebSocketServer.sendInfo(message,hotelId);
} catch (IOException e) {
e.printStackTrace();
}
}
前台页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
<link rel="shortcut icon" href="#" />
<script type="text/javascript" src="../js/jquery.min.js"></script>
<link rel="stylesheet" href="../kindeditor/themes/default/default.css" />
<script type="text/javascript" src="../kindeditor/kindeditor-all-min.js"></script>
<script type="text/javascript" src="../kindeditor/lang/zh-CN.js"></script>
</head>
<body>
<div id="demo1">
<h2>这是首页测试</h2>
<h3 id="demo2"></h3>
<audio id="audio">
<!--<source src="http://fs.w.kugou.com/201810072005/027701698f293e893c62a1d88e1d539f/G130/M05/12/00/YpQEAFrxTvOAQ8I-ADrUXaC6U88058.mp3" type="audio/mpeg">-->
<source src="http://data.huiyi8.com/yinxiao/mp3/83121.mp3" type="audio/mpeg">
</audio>
<label for="mul_input"></label><textarea id="mul_input" name="content" style="width:700px;height:200px;visibility:hidden;display: block;">KindEditor</textarea>
<script>
//简单模式初始化
var editor;
KindEditor.ready(function(K) {
editor = K.create('textarea[name="content"]', {
resizeType : 1,
allowPreviewEmoticons : false,
allowImageUpload : false,
items : [
'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
'insertunorderedlist', '|', 'emoticons', 'image', 'link']
});
});
</script>
</div>
<script>
//音频控制
var aud = document.getElementById("audio");
var socket;
if(typeof(WebSocket) === "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于
socket = new WebSocket("ws://localhost:80/websocket/21");
// socket = new WebSocket("${basePath}websocket/22".replace("http","ws"));
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {
aud.play();
console.log(msg.data);
// document.getElementById("demo2").innerText = msg.data;
var demo = document.getElementById("demo1");
var h2 = document.createElement("h2");
h2.innerHTML = msg.data;
demo.appendChild(h2);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
</script>
</body>
</html>