Websocket合并,解决页面多个websocket连接问题
背景
1. 打开首页会发起多次websocket连接,每个都调用后端各自的websocket进行;
2. 其他子页面是嵌套在主页里的,打开子页面会发起子页面里的websocket连接;
3. 想把前端和后端:一个页面内的多个websocket和其他子页面的websocket 合并成一个。
一. 前端页面合并
- 在首页创建一个websoclet连接,不同的websocket连接设定不同的type,在onopen方法里进行多次send(type,替代多个不同websocket发送不同类型消息的效果。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35var mysocket = null; function createWebsocket(){ var webUrl = window.location.host; if('WebSocket' in window){ if(mysocket==null){ mysocket = new WebSocket("ws://${xxx}/xxx?type="+type); mysocket.onopen = function(){ //可以把每个页面的websocket要传的参数设置成type的值 myscoket.send("type"); mysocket.send("type1"); } mysocket.onmessage = function(msg){ //根据拿到的type执行不同的回调函数 var type = ($.paiseJSON(msg.data)).type; if(type==xxx){ xxx; } if(type==xxx1){ xxx; } } mysocket.onclose = function(){ alert("连接关闭") } mysocket.onbeforeunload = function(){ mysocket.close(); } }else{ $.message.show({ title:'提示', msg:'浏览器版本过低,系统不支持' }); } }
二.后端合并多个websocket
> 根据前端传的type,onopen和onmessage方法里执行不同的方法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39@ServerEndpoint(value="/xxx/{param}",configurator = GetHttpSessionConfigurator.class) public class MyWebSocketServlet{ private static final long serivalVersionUID = xxx; @OnOpen//客户端链接成功后讲其保存在线程安全的集合中 public void open(Session session,EdpointConfig config,@PathParam("param")String param){ try{ param = (String)config.getUserProperties().get("type"); }catch(Exception e){ e.printStackTrace(); } //根据页面传的type进行判断,执行方法 if(param.equals("xxx")){ HttpSession httpSession = (HttpSession)config.getUserPropertie().get(HttpSession.class.getName()); AuthUser user = (AuthUser)httpSession.getAttribute(Constans.LOGIN_USER); MessageCenter.getInstance().addUserSession(session,user.getUsername()); } if(param.equals("xxx1")){ xxx; } } @OnMessage//给客户端发送消息 public void handlerMessage(String message,Sesion session){ //可以用startWith对message进行判断,然后执行对应的方法 if(message.startWith("xxx")){ xxx; } } @OnClose//客户端断开链接后将其从线程安全的集合中移除 public void onClose() { sessions.remove(this); } @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } }
思路大概就是这样,封装多个websocket,根据type进行动态的执行对应方法
最后
以上就是呆萌早晨最近收集整理的关于合并多个Websocket在一个页面,根据Type收发不同类型的消息的全部内容,更多相关合并多个Websocket在一个页面,根据Type收发不同类型内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复