WebSocket

接上文,现在想到的解决方案是,使用websocket,创建一个本地exe程序为websocket服务器端,网页端为websocket客户端,使用websocket技术,可以跨浏览器,因为现在的浏览器都是支持websocket的,也不必为google浏览器,firefox浏览器,等浏览器进行插件的定制,而且websocket具有实时性。

    使用开源库websocketpp进行开发

websocketpp需要openssl和boost库,openssl之前已经编译过了,boost库编译过程如下:

1.下载最新版boost     63

2.打开VS2008,选择“Tools”(工具)->“Visual Studio 2008 command prompt”(命令提示),进入命令行界面。

3.cd到“F:Program Fileoost_1_63_0”,运行bootstrap.bat。

4.成功后会生成bjam.exe文件。在命令行中输入以下命令进行编译:

 bjam stage --toolset=msvc-9.0 --without-graph --without-graph_parallel --without-math --without-mpi --without-python --without-serialization --without-wave --stagedir="D:Program Fileoost_1_55_0invc9" link=static runtime-link=shared runtime-link=static threading=multi debug release

 等待好长时间后,编译完成

5.选择“Tools”(工具)->“Options”(选项)->“Projects and solutions”(项目和解决方案)->“VC ++ directories”(VC++目录)。

     配置Include(包含文件)目录,增加D:oost_1_63_0inv9include     下载的源码目录里

     配置Library(库文件)目录,增加F:oost_1_63_0inv9lib           编译好的目录里

  使用websocketpp库进行开发

新建win32控制台工程,将websocketpp-0.6.0examplesprint_server中的print_server.hpp,复制到工程中,编译运行

<!DOCTYPE html>  
<meta charset="utf-8" />  
<title>WebSocket Test</title>  
<script language="javascript"type="text/javascript">  
    var wsUri ="ws://localhost:9002"; 
    var output;  
    
    function init() { 
        output = document.getElementById("output"); 
        testWebSocket(); 
    }  
 
    function testWebSocket() { 
        websocket = new WebSocket(wsUri); 
        websocket.onopen = function(evt) { 
            onOpen(evt) 
        }; 
        websocket.onclose = function(evt) { 
            onClose(evt) 
        }; 
        websocket.onmessage = function(evt) { 
            onMessage(evt) 
        }; 
        websocket.onerror = function(evt) { 
            onError(evt) 
        }; 
    }  
 
    function onOpen(evt) { 
        writeToScreen("CONNECTED"); 
        doSend("WebSocket rocks"); 
    }  
 
    function onClose(evt) { 
        writeToScreen("DISCONNECTED"); 
    }  
 
    function onMessage(evt) { 
        writeToScreen('<span style="color: blue;">RESPONSE: '+ evt.data+'</span>'); 
        //websocket.close(); 
    }  
 
    function onError(evt) { 
        writeToScreen('<span style="color: red;">ERROR:</span> '+ evt.data); 
    }  
 
    function doSend(message) { 
        writeToScreen("SENT: " + message);  
        websocket.send(message); 
    }  
 
    function writeToScreen(message) { 
        var pre = document.createElement("p"); 
        pre.style.wordWrap = "break-word"; 
        pre.innerHTML = message; 
        output.appendChild(pre); 
    }  
 
    window.addEventListener("load", init, false);  
</script>  
<h2>WebSocket Test</h2>  
<div id="output"></div>  
</html>

 本段代码解读参照:http://www.xyhtml5.com/websocket-javascript-example.html

通信速度测试每秒可以发送200+条,满足需求

原文地址:https://www.cnblogs.com/nightnine/p/6323725.html