WebSocket :用WebSocket实现推送你必须考虑的几个问题 您所在的位置:网站首页 一加消息推送延迟怎么办 WebSocket :用WebSocket实现推送你必须考虑的几个问题

WebSocket :用WebSocket实现推送你必须考虑的几个问题

2024-07-18 00:09| 来源: 网络整理| 查看: 265

目录:

目录WebSocket简介项目背景硬件环境及客户端支持本文研究内容基于javaxwebsocket服务端代码源码后续补充git连接客户端代码问题探索8月3日补充 中间线路断网情况如何做到支持几千个client同时在线人数后续8月3日补充相关测试

1.WebSocket简介

WebSocket_百度百科

2.项目背景、硬件环境及客户端支持

本项目通过WebSocket实现同时在线用户量几千的推送服务器(可内网运行)。且可实时查看用户在线状态。

服务器:centos 6.5、tomcat 7客户端:移动端(安卓、IOS)、网页端。服务端第三方库 :javax.websocket 3.本文研究内容

应用的线上环境后各种异常情况处理:

使用WebSocket时,依赖TCP keepalive还是做业务层心跳服务器如何感知客户端断开(用以查看实时用户在线状态)客户端如何感知服务端异常(用以决定客户端何时重连) 4.基于javax.websocket服务端代码(源码后续补充git连接)

WebSocketServer.java

package cn.milo.wsdemo; import org.apache.log4j.Logger; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; /* * create : 17-07-21 * auth : milo */ @ServerEndpoint("/connect/{userId}") public class WebSocketServer { private static Logger log = Logger.getLogger(WebSocketServer.class); /* New Connected */ @OnOpen public void onOpen(@PathParam("userId") String userId , Session session){ log.info("[WebSocketServer] Connected : userId = "+ userId); WebSocketUtils.add(userId , session); } /* Send Message */ @OnMessage public String onMessage(@PathParam("userId") String userId, String message) { log.info("[WebSocketServer] Received Message : userId = "+ userId + " , message = " + message); if (message.equals("&")){ return "&"; }else{ WebSocketUtils.receive(userId , message); return "Got your message ("+ message +")."; } } /* Errot */ @OnError public void onError(@PathParam("userId") String userId, Throwable throwable, Session session) { log.info("[WebSocketServer] Connection Exception : userId = "+ userId + " , throwable = " + throwable.getMessage()); WebSocketUtils.remove(userId); } /* Close Connection */ @OnClose public void onClose(@PathParam("userId") String userId, Session session) { log.info("[WebSocketServer] Close Connection : userId = " + userId); WebSocketUtils.remove(userId); } }

WebSocketUtils.java

package cn.milo.wsdemo; import cn.milo.FileUtils.CreateFile; import org.apache.log4j.Logger; import javax.websocket.Session; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class WebSocketUtils { private static Logger log = Logger.getLogger(WebSocketUtils.class); public static Map clients = new ConcurrentHashMap(); /* Add Session */ public static void add(String userId, Session session) { clients.put(userId,session); log.info("当前连接数 = " + clients.size()); } /* Receive Message */ public static void receive(String userId, String message) { log.info("收到消息 : UserId = " + userId + " , Message = " + message); log.info("当前连接数 = " + clients.size()); } /* Remove Session */ public static void remove(String userId) { clients.remove(userId); log.info("当前连接数 = " + clients.size()); } /* Get Session */ public static boolean sendMessage(String userId , String message) { log.info("当前连接数 = " + clients.size()); if(clients.get(userId) == null){ return false; }else{ clients.get(userId).getAsyncRemote().sendText(message); return true; } } } 5.客户端代码 server地址 : 您的用户id : 连接 ===================================================== 消息 : 发送 ===================================================== 连接状态 : 清空 ===================================================== 收到消息 : ===================================================== 心跳 : var heartflag = false; var webSocket = null; var tryTime = 0; $(function () { // initSocket(); window.onbeforeunload = function () { }; }); /** * 初始化websocket,建立连接 */ function initSocket() { var serveraddress = $("#serveraddress").val(); var userId = $("#userId").val(); if (!window.WebSocket) { $("#connectStatu").append(getNowFormatDate()+" 您的浏览器不支持ws"); return false; } webSocket = new WebSocket(serveraddress+"/"+userId); // 收到服务端消息 webSocket.onmessage = function (msg) { if(msg.data == "&"){ }else{ $("#receivedMessage").append(getNowFormatDate()+" 收到消息 : "+msg.data+""); } }; // 异常 webSocket.onerror = function (event) { heartflag = false; $("#connectStatu").append(getNowFormatDate()+" 异常"); }; // 建立连接 webSocket.onopen = function (event) { heartflag = true; heart(); $("#connectStatu").append(getNowFormatDate()+" 建立连接成功"); tryTime = 0; }; // 断线重连 webSocket.onclose = function () { heartflag = false; // 重试10次,每次之间间隔10秒 if (tryTime < 10) { setTimeout(function () { webSocket = null; tryTime++; initSocket(); $("#connectStatu").append( getNowFormatDate()+" 第"+tryTime+"次重连"); }, 3*1000); } else { alert("重连失败."); } }; } function send(){ var message = $("#message").val(); webSocket.send(message); } function clearConnectStatu(){ $("#connectStatu").empty(); } function getNowFormatDate() { var date = new Date(); var seperator1 = "-"; var seperator2 = ":"; var month = date.getMonth() + 1; var strDate = date.getDate(); if (month >= 1 && month = 0 && strDate


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有