统的HTTP都是基于请求响应模型的,客户端和服务器端无法实现实时通信。之前有一种模仿实时通信的技术,从轮循、长轮循到comet都不能彻底解决问题。WebSocket的出现改变了现状,上百倍的减少通信中无用的消息头,极大的提高了通信效率的同时也提供了非常低地的延时。
WebSocket请求和回复的消息头如下:
原书上有一个python写的简单的WebSocket EchoServer的实现,我就不贴代码了,大家用Nodejs实验吧。
检测浏览器支持:
- function loadDemo() {
- if (window.WebSocket) {
- document.getElementById("support").innerHTML = "HTML5 WebSocket is supported in your browser.";
- } else {
- document.getElementById("support").innerHTML = "HTML5 WebSocket is not supported in your browser.";
- }
- }
- <!DOCTYPE html>
- <title>WebSocket Test Page</title>
- <script>
- var log = function(s) {
- if (document.readyState !== "complete") {
- log.buffer.push(s);
- } else {
- document.getElementById("output").innerHTML += (s + "\n");
- }
- }
- log.buffer = [];
- url = "ws://localhost:8080/echo";
- w = new WebSocket(url);
- w.onopen = function() {
- log("open");
- w.send("thank you for accepting this WebSocket request");
- }
- w.onmessage = function(e) {
- log(e.data);
- }
- w.onclose = function(e) {
- log("closed");
- }
- window.onload = function() {
- log(log.buffer.join("\n"));
- document.getElementById("sendButton").onclick = function() {
- w.send(document.getElementById("inputMessage").value);
- }
- }
- </script>
- <input type="text" id="inputMessage" value="Hello, WebSocket!"><button
- id="sendButton">Send</button>
- <pre id="output"></pre>