Web Sockets的目標是在一個單獨的持久鏈接上提供全雙工、雙向通訊。javascript
在JavaScript中建立了Web Socket以後,會有一個HTTP請求發送到瀏覽器以發起鏈接。在取得服務器的響應後,創建的鏈接會使用HTTP升級從HTTP協議交換爲Web Socket協議。php
也就是說,使用標準的HTTP服務器沒法實現Web Socket,只有支持這種協議的專門服務器才能正常工做。html
注意:java
一、Web Socket使用自定義的協議,http:// —— >ws ://;https://——>wss://;node
二、使用Web Socket jquery
1、要建立Web Socket,首先要實例一個WebSocket對象並傳入要鏈接的URL: var socket = new WebSocket("ws://www.example.com/server.php"); 注意:同源策略對Web Sockets不適用,所以能夠經過它打開到任何站點的鏈接,是否通訊取決於服務器。 建立對象以後,瀏覽器會嘗試建立鏈接,與XHR累死,WebSocket也有一個表示當前狀態的readyState屬性。 以下狀態: WebSocket.OPENING(0) : 正在創建鏈接。 WebSocket.OPENING(1) : 已經創建鏈接。 WebSocket.CLOSING(2) : 正在關閉鏈接。 WebSocket.CLOSING(3) : 已經關閉鏈接。 WebSocket沒有readyStatechange事件。 能夠使用close()方法來關閉鏈接。 socket.close(); 2、發送和接收數據 使用***send();***來發送數據。 socket.send("Hello world!"); 由於WebSockets只能經過鏈接發送***連續***的純文本數據,因此對於複雜的數據結構,發送以前要進行序列化。 以下序列化爲JSON字符串,再發送到數據庫。 var message = { time:new Date(), text:"Hello world", clientId:"sdfdsfsdfdf" }; socket.send(JSON.stringify(message)); 服務器接收到發送來的數據以後,接着WebSocket對象就會觸發 message 事件。 而後把數據保存在event.data屬性中,發送給瀏覽器端。 瀏覽器端接收到服務器發來的數據,須要先解析發來的字符串。 socket.onmessage = function(event){ var data = event.data ; //處理數據 } 3、其餘事件 WebSocket 還有其餘三個事件,在鏈接的生命週期的不一樣階段觸發。 open:成功創建鏈接時觸發。 error:發生錯誤時觸發,鏈接不能持續。 close:鏈接關閉時觸發。 socket.onopen = function(){}; socket.onerror = function(){}; socket.onclose = function(){}; 不支持Dom2級事件偵聽器,所以只能使用Dom0級的語法定義每一個事件處理程序。 這三個事件有三個額外的屬性: wasClean:布爾值,表示鏈接是否已關閉, code:服務器返回的數值狀態碼, reason:字符串,包含服務器發回的消息。 socket.onclose = function(event){ console.log("Was clean?" + event.waxClean + " Code=" + event.code + " Reason=" + event.reason); };
基本內容跟以前的講解同樣,客戶端與服務端消息的發送都是: socket.send();git
接收都是綁定到事件onmessage上:socket.onmessage = function(e){var message = e.data;//message就是接受到的數據}github
介紹了一個實例以下:web
wschatserver.js:服務代碼數據庫
/* * This is server-side JavaScript, intended to be run with NodeJS. * It runs a WebSocket server on top of an HTTP server, using an external * websocket library from https://github.com/miksago/node-websocket-server/ * If it gets an HTTP request for "/" it returns the chat client HTML file. * Any other HTTP requests return 404. Messages received via the * WebSocket protocol are simply broadcast to all active connections. */ var http = require('http'); // Use Node's HTTP server API var ws = require('node-websocket-server'); // Use an external WebSocket library // Read the source of the chat client at startup. Used below. var clientui = require('fs').readFileSync("wschatclient.html"); // Create an HTTP server var httpserver = new http.Server(); // When the HTTP server gets a new request, run this function httpserver.on("request", function (request, response) { // If the request was for "/", send the client-side chat UI. if (request.url === "/") { // A request for the chat UI response.writeHead(200, {"Content-Type": "text/html"}); response.write(clientui); response.end(); } else { // Send a 404 "Not Found" code for any other request response.writeHead(404); response.end(); } }); // Now wrap a WebSocket server around the HTTP server var wsserver = ws.createServer({server: httpserver}); // Call this function when we receive a new connection request wsserver.on("connection", function(socket) { socket.send("Welcome to the chat room."); // Greet the new client socket.on("message", function(msg) { // Listen for msgs from the client console.log(msg); wsserver.broadcast(msg); // And broadcast them to everyone }); }); // Run the server on port 8000. Starting the WebSocket server starts the // HTTP server as well. Connect to http://localhost:8000/ to use it. wsserver.listen(7000);
wschatclient.html 瀏覽器呈現頁面
<script> window.onload = function() { // Take care of some UI details var nick = prompt("Enter your nickname"); // Get user's nickname var input = document.getElementById("input"); // Find the input field input.focus(); // Set keyboard focus // Open a WebSocket to send and receive chat messages on. // Assume that the HTTP server we were downloaded from also functions as // a websocket server, and use the same host name and port, but change // from the http:// protocol to ws:// var socket = new WebSocket("ws://" + location.host + "/"); // This is how we receive messages from the server through the web socket socket.onmessage = function(event) { // When a new message arrives var msg = event.data; // Get text from event object var node = document.createTextNode(msg); // Make it into a text node var div = document.createElement("div"); // Create a <div> div.appendChild(node); // Add text node to div document.body.insertBefore(div, input); // And add div before input input.scrollIntoView(); // Ensure input elt is visible } // This is how we send messages to the server through the web socket input.onchange = function() { // When user strikes return var msg = nick + ": " + input.value; // Username plus user's input socket.send(msg); // Send it through the socket input.value = ""; // Get ready for more input } }; </script> <!-- The chat UI is just a single, wide text input field --> <!-- New chat messages will be inserted before this element --> <input id="input" style="width:100%"/>
安裝node-websocket-server模塊,原來的寫的是websocket-server模塊,可是有問題,換成這個模塊以後,頁面能夠加載出來,可是好像不能發送消息,之後有時間了再看看,這原生的實現。
目前不能實現傳遞,不太明白什麼緣由。應該是這個模塊使用方法不對。
如下實例使用socket.io能夠實現多個頁面與服務端的通訊
app.js
//app.js var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var path = require('path'); app.get('/', function(req, res){ res.sendFile(path.join(__dirname, 'index.html')); }); io.on('connection', function(socket){ console.log('a user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); socket.on('chat messages', function(msg){ console.log('message: ' + msg); io.emit('chat messages', msg); }); }); app.set('port', process.env.PORT || 3000); var server = http.listen(app.get('port'), function() { console.log('start at port:' + server.address().port); });
index.html
<!doctype html> <html> <head> <meta charset = "utf-8"> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="/socket.io/socket.io.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> <script> var socket = io(); $('form').submit(function(){ socket.emit('chat messages', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat messages', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> </body> </html>
使用須要安裝模塊: socket.io express