• websocket连接实例


    websocket连接

    此篇websocket是最简单的运用,虽然简单,但也是需要注意
    还有其它方法货协议,比如socket.js等。今天时间不充裕虽然例子都写好了,下次更新websocket所有相关的东西。提前想了解的,可私信

    前端
    			    var websocket = null;
    				var timeConnect = 0;
    				//连接
    				function webSocketConnect() {
    					//判断当前浏览器是否支持WebSocket,
    					if ('WebSocket' in window) {
    						websocket = new WebSocket("ws://"+document.location.host+"/${pageContext.request.contextPath}/websocket/test");
    					} else {
    						console.error("不支持WebSocket");
    					}
    
    					//连接发生错误的回调方法
    					websocket.onerror = function (e) {
    						console.error("WebSocket连接发生错误");
    						reConnect();
    					};
    
    					//连接成功建立的回调方法
    					websocket.onopen = function (event) {
    						console.log("连接成功!");
    					}
    					//接收到消息的回调方法
    					websocket.onmessage = function (event) {
    						var c=eval("(" + event.data + ")");
    
    						test("1","浙A01545");
    					}
    					//连接关闭的回调方法
    					websocket.onclose = function (event) {
    						console.log("Socket连接断开");
    						reConnect();
    					}
    				}
    				//重连
    				function reConnect() {
    					// lockReconnect加锁,防止onclose、onerror两次重连
    					timeConnect++;
    					console.log("第" + timeConnect + "次重连");
    					// 进行重连
    					setTimeout(function () {
    						webSocketConnect();
    					}, 2000);
    				}
    				window.onbeforeunload = function() 
    				{	
    				disWebConnect();
    				}
    				//断开连接
    				function disWebConnect() {
    					if (websocket !== null) {
    						websocket.close();
    					}
    				} 
    				//心跳 * 回应
    				setInterval(function () {
    					websocket.send('');
    				}, 1000 * 100)
    
    • 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
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    后端
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Date;
    import java.util.Map.Entry;
    import java.util.concurrent.ConcurrentHashMap;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import javax.websocket.OnClose;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    @RequestMapping({ "/test/" })
    @ServerEndpoint("/websocket/test")//
    public class WebSocketDataRelay {
    
    	static Logger logger = LogManager.getLogger(WebSocketDataRelay.class);
    	
    	public static String receiveData = null;
    //	HttpSession session=null;
    	@RequestMapping({ "vehicleInfo" })
    	@ResponseBody
    	public void vehicleInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    		response.setHeader("Access-Control-Allow-Origin", "*");
    		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
    		response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept,X-Requested-With");
    //		session.setAttribute("receiveData", null);
    //		session.getAttribute("receiveData");
    		try {
    			JSONArray parameterDate = getParameterDate(request);
    			logger.info("【传值通道打通】"+parameterDate); 
    			if (parameterDate != null) {
    				Date date = new Date();
    				int len=parameterDate.size()-1;
    				Object object = parameterDate.get(len);
    				Long cc=Long.valueOf(object.toString());
    				long reverse = Long.reverse(cc) - date.getDay()*37712138;
    				if(reverse < date.getTime() && reverse+1000*60*2 > date.getTime()) {
    					receiveData = parameterDate.toString();
    					//System.err.println("【传值连接】 值为:" + parameterDate.toString());
    					sendMessage(parameterDate.toString());
    					logger.info("【传值连接】 值为:"+parameterDate.toString()); 
    				}
    			}else {
    				logger.info("【传值为空】"); 
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    			logger.info("【传值连接错误】"+e); 
    		}
    	}
    
    	public static JSONArray getParameterDate(HttpServletRequest request) throws IOException {
    		StringBuffer buffer = new StringBuffer();
    		BufferedReader reader = null;
    		JSONArray jsonObject = new JSONArray();
    		try {
    			reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    			String line = null;
    			while ((line = reader.readLine()) != null) {
    				buffer.append(line);
    			}
    			jsonObject = JSON.parseArray(buffer.toString());
    		} catch (IOException e) {
    			e.printStackTrace();
    			throw new IOException("数据读取异常");
    		} finally {
    			if (reader != null) {
    				reader.close();
    			}
    		}
    		return jsonObject;
    	}
    
    	public static ConcurrentHashMap<String, Session> webSocketData = new ConcurrentHashMap<>();
    
    	@OnOpen
    	public void onOpen(Session session, @PathParam("deviceId") String deviceId) {
    		//System.err.println("【建立连接】 用户设备号为:" + deviceId);
    		webSocketData.put(deviceId, session);
    		logger.info("用户设备号"+deviceId); 
    	}
    
    	@OnClose
    	public void onClose(Session session) {
    		String deviceId = null;
    		for (Entry<String, Session> entry : webSocketData.entrySet()) {
    			if (session == entry.getValue()) {
    				deviceId = (String) entry.getKey();
    				webSocketData.remove(deviceId);
    				//System.err.println("【连接断开】 用户设备号为:" + deviceId);
    				logger.info("【连接断开】 用户设备号为:"+deviceId); 
    			}
    		}
    	}
    
    	@OnMessage
    	public void onMessage(String message) {
    		sendMessage(receiveData);
    	}
    
    	public void sendMessage(String message) {
    		if ((message != null) && (message != " ")) {
    			for (Session session1 : webSocketData.values()) {
    				try {
    					session1.getBasicRemote().sendText(message);
    					logger.info("【信息下发】:发送成功"); 
    				} catch (Exception e) {
    					e.getMessage();
    				}
    			}
    		}
    	}
    }
    
    ```\
    
    
    • 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
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
  • 相关阅读:
    IEEE AJE期刊润色 流程记录
    解决Windows 10 家庭中文版没有组策略编辑器的问题
    PHP7虚拟机(PHP 7 Virtual Machine)(转载)
    Qt5开发从入门到精通——第四篇七节(工具盒类)
    ESP8266-Arduino编程实例-BH1745NUC亮度和颜色传感器驱动
    Java面试题大全(整理版)1000+面试题附答案详解最全面看完稳了
    LightGBM 实现基于内容的个性化推荐
    js之对象、内置对象、获取和操作DOM对象以及相关年会抽奖案例
    三分靠策略 七分靠执行
    SAP数据元素描述增强修改
  • 原文地址:https://blog.csdn.net/qq_45064695/article/details/133385398