我是靠谱客的博主 自信酸奶,最近开发中收集的这篇文章主要介绍Websocket根据session向客户端推送不同数据 巧妙使用菜鸟HTML,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

代码:
客户端:

<!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>
<button onclick="conagain();">改变条件</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?username=admin");
} else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
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 closeWebSocket(){
alert("数据关闭!!!!!!!!");
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
alert(message);
websocket.send(message);
}
function conagain(){
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
alert('当前浏览器支持 websocket');
websocket = new WebSocket("ws://localhost:8999/earlyWarningWebSocket?username=admin");
} else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
setMessageInnerHTML("WebSocket连接成功");
var message = document.getElementById('text').value;
alert(message);
websocket.send(message)
}
//接收到消息的回调方法
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 closeWebSocket(){
alert("关闭连接");
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
alert(message);
websocket.send(message);
}
}
</script>
</html>

服务端:

package com.zhuoshi.jcbigdata.websocket;
import java.io.IOException;
import java.util.ArrayList;
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 com.alibaba.fastjson.JSONObject;
import com.zhuoshi.jcbigdata.util.DateUtil;
import com.zhuoshi.jcbigdata.util.PropertiesMoreUtils;
import com.zhuoshi.jcbigdata.util.RedisUtil;
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);
webSocketSet_map.put(username, this);
addOnlineCount();
}
@OnClose
public void onClose() {
try {
System.out.println("关闭一个连接!!!!!!!!");
webSocketSet.remove(this);
//将map中的sessionid移除
//sessionmessage.remove(this.session.getId());
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();
String [] testlast=message.split("#");
String teslsatstr= testlast[testlast.length-1];
//将sessionid 存入map
sessionmessage.put(teslsatstr, message);
//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()) {
//清空已推送数据
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 alarmmaplist
* @param message
*/
public void setReal(List<Map<String, String>> alarmmaplist,String message) {
String nowtime=DateUtil.NowDate();//获取当前时间
String yesterday=DateUtil.getDayBeforeOfNow();//获取前一天日期
//处理message 将点位坐标id和布控类型id使用#隔开
String [] allmmessage=message.split("#");
String sectionid=allmmessage[0];
String vehicleType=allmmessage[1];
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
}
}
}
}*/
}
}

最后

以上就是自信酸奶为你收集整理的Websocket根据session向客户端推送不同数据 巧妙使用菜鸟HTML的全部内容,希望文章能够帮你解决Websocket根据session向客户端推送不同数据 巧妙使用菜鸟HTML所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部