how2j.cn

步骤 1 : 效果   
步骤 2 : WebSocket概念   
步骤 3 : 优点   

步骤 1 :

效果

如图所示,当服务端有新的比特币价格后,浏览器马上就可以看到最新的数据。
"); window.frames["iframe_show7056"].document.write(decodeHtml($("textarea#stepcodeTextarea7056").val())); window.frames["iframe_show7056"].document.close(); $(window.frames["iframe_show7056"]).load(function(){ $("#iframe_show7056").height($("#iframe_show7056").contents().find("body").height()+showittryitheight); }); $("#iframe_show7056").height($("#iframe_show7056").contents().find("body").height()+showittryitheight); setTimeout(function(){ },500); });
<!DOCTYPE html> <html> <head> <title>用WebSocket实时获知比特币价格</title> </head> <body> <div style="width:400px;margin:20px auto;border:1px solid lightgray;padding:20px;text-align:center;"> 当前比特币价格:¥<span style="color:#FF7519" id="price">10000</span> <div style="font-size:0.9em;margin-top:20px">查看的人数越多,价格越高, 当前总共 <span id="total">1</span> 个人在线</div> <div style="color:silver;font-size:0.8em;margin-top:20px">以上价格纯属虚构,如有雷同,so what?</div> </div> </body> <script type="text/javascript"> var websocket = null; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://how2j.cn/ws/bitcoinServer"); //连接成功建立的回调方法 websocket.onopen = function () { websocket.send("客户端链接成功"); } //接收到消息的回调方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //连接发生错误的回调方法 websocket.onerror = function () { alert("WebSocket连接发生错误"); }; //连接关闭的回调方法 websocket.onclose = function () { //alert("WebSocket连接关闭"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { closeWebSocket(); } } else { alert('当前浏览器 Not support websocket') } //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { var bitcoin = eval("("+innerHTML+")"); document.getElementById('price').innerHTML = bitcoin.price; document.getElementById('total').innerHTML = bitcoin.total; } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } </script> </html>
"); window.frames["iframe7056"].document.write(decodeHtml(code7056)); window.frames["iframe7056"].document.close(); //load和下面的非load必需并存,因为如果代码用到了jquery就必须使用load的方式 $(window.frames["iframe7056"]).load(function(){ $("#iframe7056").height($("#iframe7056").contents().find("body").height()+showittryitheight); }); $("#iframe7056").height($("#iframe7056").contents().find("body").height()+showittryitheight); alreadyWriteCode7056 = code7056; $("#rendering7056").hide(); $("#rendered7056").show(); } var tRereshRetry2DemoPanel7056 = setInterval(rereshRetry2DemoPanel7056,1000); var binded7056 = false; $("textarea#stepcodeTextarea7056").keyup(function(){ if(!binded7056){ $(window).bind('beforeunload',function(){ binded7056 = true; return "xxxx"; }); } var newCode = $(this).val() code7056 = newCode; /*below code is replaced by function rereshRetry2DemoPanel()*/ // if(code7056!=newCode){ // window.frames["iframe7056"].document.write("
"); // window.frames["iframe7056"].document.write(decodeHtml($("textarea#stepcodeTextarea7056").val())); // window.frames["iframe7056"].document.close(); // $(window.frames["iframe7056"]).load(function(){ // $("#iframe7056").height($("#iframe7056").contents().find("body").height()+showittryitheight); // }); // code7056 = newCode; // } }); $(".tryButton7056").click(function(){ $("#tryDiv7056").show(); $("#stepcodeTextarea7056").focus(); $("#stepcodeTextarea7056").height(200); $("#iframe7056").height(0); window.frames["iframe7056"].document.write("
"); window.frames["iframe7056"].document.write(decodeHtml($("textarea#stepcodeTextarea7056").val())); window.frames["iframe7056"].document.close(); //load和下面的非load必需并存,因为如果代码用到了jquery就必须使用load的方式 $(window.frames["iframe7056"]).load(function(){ $("#iframe7056").height($("#iframe7056").contents().find("body").height()+showittryitheight); }); $("#iframe7056").height($("#iframe7056").contents().find("body").height()+showittryitheight); this.scrollIntoView(true); editor7056.focus(); editor7056.setSize(null, "250"); $("#rendering7056").hide(); $("#rendered7056").hide(); }); var mixedMode = { name: "htmlmixed", scriptTypes: [{matches: /\/x-handlebars-template|\/x-mustache/i, mode: null}, {matches: /(text|application)\/(x-)?vb(a|script)/i, mode: "vbscript"}] }; var editor7056 = CodeMirror.fromTextArea(document.getElementById("stepcodeTextarea7056"), { lineNumbers: true, styleActiveLine: true, matchBrackets: true, mode:"text/html", theme:"eclipse", selectionPointer: true, lineWrapping: true, extraKeys: { "Alt-/": "autocomplete", "Ctrl-F": "findPersistent", "F8": function(cm) { cm.setOption("fullScreen", !cm.getOption("fullScreen")); }, "Esc": function(cm) { if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false); } } }); editor7056.on("change",function(doc){ if(!binded7056){ $(window).bind('beforeunload',function(){ binded7056 = true; return "xxxx"; }); } var newCode = doc.getValue(); code7056 = newCode; $("textarea#stepcodeTextarea7056").val(newCode); if(alreadyWriteCode7056!=code7056){ lastModifedTime7056 = new Date().getTime(); $("#rendering7056").show(); $("#rendered7056").hide(); } // alert(doc.getValue()); }); $(".CodeMirror").addClass("form-control"); // var editor7056 = CodeMirror.fromTextArea(, { // lineNumbers: true, // styleActiveLine: true, // matchBrackets: true, // theme:"eclipse", // }); editor7056.on("change",function(doc){ // alert(doc.getValue()); }); $("#tryDiv7056").hide(); }); $("div.codemirrorTips span").addClass("glyphicon glyphicon-asterisk");


源代码
1. 双击选中单词 2. 三击选中整行 3. CTRL+F 查找 4. F8 全屏编辑,再次点击恢复
渲染中 渲染完成
效果
步骤 2 :

WebSocket概念

在WebSocket概念出来之前,如果页面要不停地显示最新的价格,那么必须不停地刷新页面,或者用一段js代码每隔几秒钟发消息询问服务器数据。

而使用WebSocket技术之后,当服务器有了新的数据,会主动通知浏览器。 如效果所示,当服务端有新的比特币价格之后,浏览器立马接收到消息。
步骤 3 :

优点

1. 节约带宽。 不停地轮询服务端数据这种方式,使用的是http协议,head信息很大,有效数据占比低, 而使用WebSocket方式,头信息很小,有效数据占比高。
2. 无浪费。 轮询方式有可能轮询10次,才碰到服务端数据更新,那么前9次都白轮询了,因为没有拿到变化的数据。 而WebSocket是由服务器主动回发,来的都是新数据。
3. 实时性,考虑到服务器压力,使用轮询方式不可能很短的时间间隔,否则服务器压力太多,所以轮询时间间隔都比较长,好几秒,设置十几秒。 而WebSocket是由服务器主动推送过来,实时性是最高的


HOW2J公众号,关注后实时获知布最新的教程和优惠活动,谢谢。


关于 工具和中间件-WebSocket-演示 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 620943819
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: http://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图