Websocket根据session向客户端推送不同数据 巧妙使用菜鸟HTML
程序员文章站
2022-06-06 09:49:07
...
代码:
<!DOCTYPE html>
<html>
<head>
<title>new document</title>
<meta name="generator" content="editplus" />
<meta name="author" content="" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="jquery-2.0.3.min.js" type="text/javascript"></script>
</head>
<body>
<center>
Welcome<br />
<input id="text" type="text" />
<button onclick="send()">发送消息</button>
<hr />
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr />
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
alert('当前浏览器支持 websocket');
websocket = new WebSocket("ws://localhost:8999/earlyWarningWebSocket");
} else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
alert("WebSocket连接成功")
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭WebSocket连接
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
//websocket.close();
};
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
package com.zhuoshi.jcbigdata.websocket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import com.alibaba.fastjson.JSONObject;
import com.sun.tools.doclets.internal.toolkit.MemberSummaryWriter;
import com.zhuoshi.jcbigdata.service.real.RealAnalyzeService;
import com.zhuoshi.jcbigdata.util.DateUtil;
import com.zhuoshi.jcbigdata.util.PropertiesMoreUtils;
import com.zhuoshi.jcbigdata.util.RedisUtil;
import com.zhuoshi.jcbigdata.util.StringSwitchMap;
import ch.qos.logback.core.net.SyslogOutputStream;
import redis.clients.jedis.JedisCluster;
/*
* 首页实时数据推送
* @author Administrator
*
*/
@ServerEndpoint("/earlyWarningWebSocket")
@Component
public class EarlyWarningWebSocket {
private static int onlineCount = 0;
int curr_lenth = 0;
private static CopyOnWriteArraySet<EarlyWarningWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
private static Map<String, EarlyWarningWebSocket> webSocketSet_map = new HashMap<String, EarlyWarningWebSocket>();
private static Map<Object, String> sessionmessage = new HashMap<Object, String>();
private static String image_url = PropertiesMoreUtils.getInstance().get("sys", "ShowImageUrl", "");
private Session session;
JedisCluster jedis;
@OnOpen
public void onOpen(Session session) {
System.out.println("session"+session);
jedis = RedisUtil.getRedisUtil().getJedis();
this.session = session;
webSocketSet.add(this);
System.out.println("开始连接!!!!!!!!!!!!!!!!!!");
/* Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
List<String> list = requestParameterMap.get("username");
String username = list.get(0); // 当前用户名
webSocketSet_map.put(username, this);*/
String sessonid=session.getId();
webSocketSet_map.put(sessonid, this);
addOnlineCount();
}
@OnClose
public void onClose() {
try {
webSocketSet.remove(this);
subOnlineCount();
} catch (Exception e) {
e.printStackTrace();
}
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("前端返回数据::::"+message);
/*Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
List<String> list = requestParameterMap.get("username");
String username = list.get(0); // 当前用户名*/
String sessionid=session.getId();
//将sessionid 存入map
sessionmessage.put(sessionid, message);
//根据sessionID 获取当前类
EarlyWarningWebSocket shouyeWebSocket = null ;
List<Map<String, String>> alarmmaplist = new ArrayList<Map<String, String>>();
try {
for(Object key : sessionmessage.keySet()) { //根据不同条件取值推送数据
setReal(alarmmaplist,sessionmessage.get(key));
Object json = JSONObject.toJSON(alarmmaplist);
//发送数据
shouyeWebSocket= webSocketSet_map.get(key);
shouyeWebSocket.sendMessage(json.toString());
alarmmaplist.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
//根据不同条件取值推送数据
for(Object key : sessionmessage.keySet()) {
//清空已推送数据
System.out.println("key"+key);
setReal(alarmmaplist,sessionmessage.get(key));
Object json = JSONObject.toJSON(alarmmaplist);
shouyeWebSocket= webSocketSet_map.get(key);
shouyeWebSocket.sendMessage(json.toString());
alarmmaplist.clear();
}
Thread.sleep(1000);
}
} catch (Exception e) {
Thread.interrupted();//中断请求
shouyeWebSocket.onClose();//关闭webscoket连接
}
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return EarlyWarningWebSocket.onlineCount;
}
public static synchronized void addOnlineCount() {
EarlyWarningWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
EarlyWarningWebSocket.onlineCount--;
}
@OnError
public void onError(Session session, Throwable thr) {
}
/**
*
* @param real_hashMap
*/
public void setReal(List<Map<String, String>> alarmmaplist,String message) {
String nowtime=DateUtil.NowDate();//获取当前时间
String yesterday=DateUtil.getDayBeforeOfNow();//获取前一天日期
//System.out.println("-------推送报警弹出框数据------");
//处理message 将点位坐标id和布控类型id使用^隔开
String [] allmmessage=message.split("#");
String sectionid=allmmessage[0];
System.out.println("sectionid"+sectionid);
String vehicleType=allmmessage[1];
System.out.println("vehicleType"+vehicleType);
Map test= new HashMap<>();
test.put(sectionid, sectionid);
alarmmaplist.add(test);
/* Map<String, String> alarmmap =jedis.hgetAll(nowtime+"_alarm_box");//获得报警数据
if(alarmmap.isEmpty()) {
alarmmap =jedis.hgetAll(yesterday+"_alarm_box");//获得报警数据
}
if(alarmmap.isEmpty()) {
alarmmaplist.add(alarmmap= new HashMap<String, String>());
}else {
Map<String, String> valuemap = null;
for (String key : alarmmap.keySet()) {
// System.out.println("报警获取redis中Key =" + key);
String value=alarmmap.get(key);
valuemap =new HashMap<>();
valuemap= StringSwitchMap.transStringToMap(value);
//判断是否推送完成
String pushstatus=valuemap.get("push_status");
if(pushstatus!=null&&!pushstatus.equals("")&&!pushstatus.equals("0")) {
//判断是否满足前端过滤要求(点位 布控类型)
if(sectionid.contains(valuemap.get("section_id"))&&vehicleType.contains(valuemap.get("bk_type"))) {
//System.out.println("");
String datpath=valuemap.get("data_path");
valuemap.put("data_path", image_url+valuemap.get("data_path"));
alarmmaplist.add(valuemap);
//推送完成 修改Redis的推送状态
valuemap.put("data_path",datpath);//将原有图片url 放入
valuemap.put("push_status","1");//改变推送状态
value= StringSwitchMap.transMapToString(valuemap);//将map数据转为String
jedis.hset(nowtime+"_alarm_box", key, value);//改变该key 的推送状态 存入Redis
}
}
}
}*/
}
}
上一篇: 乱序-思考-路在何方
下一篇: vue 学习教程