zoukankan      html  css  js  c++  java
  • WebSocket重连实现

    方式一、使用第三方库实现

    比如:reconnecting-websocket.js
    ReconnectingWebSocket,代码:https://github.com/joewalnes/reconnecting-websocket

    var ws = new WebSocket('ws://....');
    替换成下面的
    var ws = new ReconnectingWebSocket('ws://....');

    方式二、自己用setTimeout实现

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    
    <title>socketjs</title>
    </head>
    <body>
    发送者:<input id="fromUserId" value="2">
    接收者:<input id="toUserId" value="3">
    <button type="button" onclick="openClick();">打开</button>
    <button type="button" onclick="closeClick();">关闭</button><br/>
    <input id="message" value="---"/>
    <button type="button" onclick="sendClick();">发送</button>
    <div id="content"></div>
    <script>
    var socket;
    var t;
    var MAX = 1000;
    var count = 0;
    function openClick() {
        connection();
    }
    function closeClick() {
        socket.close();
    }
    function sendClick() {
        var fromUserId = document.getElementById("fromUserId").value;
        var toUserId = document.getElementById("toUserId").value;
        var content = document.getElementById("message").value;
        var obj = {
                "fromUserId":fromUserId,
                "toUserId":toUserId,
                "content":content
        };
        document.getElementById("content").innerHTML = document.getElementById("content").innerHTML + '<br/>' + fromUserId + "说:" + content;
        socket.send(JSON.stringify(obj));
        console.log(fromUserId + "说:" + JSON.stringify(content));
    }
    
    var connection = function() {
        var fromUserId = document.getElementById("fromUserId");
        var url = 'ws://' + window.location.host + '/ycxcode/websocket/commodity/{' + fromUserId.value + '}';
        socket = new WebSocket(url);
        socket.onopen = onopen;
        socket.onmessage = onmessage;
        socket.onclose = onclose;
        socket.onerror = onerror;
    }
    var reconnection = function() {
        count = count + 1;
        console.log("reconnection...【" + count + "");
        //1与服务器已经建立连接
        if (count >= MAX || socket.readyState == 1) {
            clearTimeout(t);
        } else {
            //2已经关闭了与服务器的连接
            if (socket.readyState == 3) {
                connection();
            }
            //0正尝试与服务器建立连接,2正在关闭与服务器的连接
            t = setTimeout(function() {reconnection();}, 100);
        }
    }
    var onopen = function() {
        console.log("open...");
    }
    var onclose = function() {
        console.log("close...");
        reconnection();
    }
    var onmessage = function(e) {
        console.log("message...");
        if (e.data === "") return;
        var toUserId = document.getElementById("toUserId").value;
        document.getElementById("content").innerHTML = document.getElementById("content").innerHTML + '<br/>' + toUserId + "说:" + e.data;
        console.log(toUserId + "说:" + e.data);
    }
    var onerror = function() {
        console.log("error...");
        reconnection();
    }
    </script>
    </body>
    </html>

    核心代码就是在onclose事件发生时调用reconnection()方法,但是要特别注意重试次数和状态控制。
    在socket.readyState == 3(已经关闭了与服务器的连接)才真正的发起连接,
    在socket.readyState == 1(与服务器已经建立连接)或重试次数超了设定值就终止重试,但要注意在终止浏览器页面及网络恢复时重刷页面
    在socket.readyState == 0(正尝试与服务器建立连接)或socket.readyState == 2(正在关闭与服务器的连接)时仅仅重试,而不发起连接

  • 相关阅读:
    Windows SDK编程(Delphi版) 之 应用基础,楔子
    一个小问题引发的论证思考
    Delphi 组件开发教程指南(7)继续模拟动画显示控件
    用PyInstaller将python转成可执行文件exe笔记
    使用 .Net Memory Profiler 诊断 .NET 应用内存泄漏(方法与实践)
    Microsof Office SharePoint 2007 工作流开发环境搭建
    How to monitor Web server performance by using counter logs in System Monitor in IIS
    LINQ之Order By
    window 性能监视器
    内存泄露检测工具
  • 原文地址:https://www.cnblogs.com/yangchongxing/p/8484939.html
Copyright © 2011-2022 走看看