what is websockets
Two-way communication over ont TCP socket, a type of PUSH technology
HTML5的新特性,用於雙向推送消息(例如網頁聊天,手機推送消息等)
原理:
- client利用regular http請求webpage
- 請求的webpage 執行javascript腳本,open a connection to server.
-
有新的信息時服務器和客戶端可以相互發送信息(Real-time traffic from the server to the client and from the client to the server

客戶端
說明:
readyState:
CONNECTING (0):表示還沒建立連接;
OPEN (1): 已經建立連接,可以進行通訊;
CLOSING (2):通過關閉握手,正在關閉連接;
CLOSED (3):連接已經關閉或無法打開;
url: WebSocket 服務器的網絡地址,協議通常是”ws”或“wss(加密通信)”,
事件:
- send:向服務器端發送數據
- close 方法就是關閉連接;
- onopen連接建立,即握手成功觸發的事件;
- onmessage收到服務器消息時觸發的事件;
- onerror異常觸發的事件;
使用例子:
// 創建一個Socket實例 var socket = new WebSocket('ws://localhost:8080'); // 打開Socket socket.onopen = function(event) { // 發送一個初始化消息 socket.send('I am the client and I\'m listening!'); // 監聽消息 socket.onmessage = function(event) { console.log('Client received a message',event); }; // 監聽Socket的關閉 socket.onclose = function(event) { console.log('Client notified socket has closed',event); }; // 關閉Socket.... //socket.close() };
服務器端
jWebSocket (Java)
web-socket-ruby (ruby)
Socket IO-node (node.js)
下面以socket.io說明,環境說明:(node.js安裝見 http://www.cnblogs.com/wishyouhappy/p/3647037.html)
1. 安裝socket.io
npm install -g socket.io
2.使用require引入http和socket.io
var http = require("http"); var io= require('socket.io');
3.創建server
var server = http.createServer(function(request, response){ response.writeHead(200,{"Content-Type":"text/html"}); response.write("WebSocket Start~~~~~~~~~~~~"); response.end(""); }).listen(8000);
4.監聽
var socket= io.listen(server);
5.例子:
var http = require("http"); var io= require('socket.io'); var server = http.createServer(function(request, response){ response.writeHead(200,{"Content-Type":"text/html"}); response.write("WebSocket Start~~~~~~~~~~~~"); response.end(""); }).listen(8000); var socket= io.listen(server); // 添加一個連接監聽器 socket.on('connection', function(client){ client.on('message',function(event){ console.log('Received message from client!',event); }); client.on('disconnect',function(){ clearInterval(interval); console.log('Server has disconnected'); }); });
數據發送兩種方式send和emit
使用send和emit都可以發送數據,但是emit可以自定義事件,如下:
emit:
//服務器 socket.on('connection', function(client){ client.on('message',function(event){ client.emit('emitMessage', { hello: 'messgge received, wish you happy'+new Date().toString() }); }); }); //客戶端 socket.on('emitMessage',function(data) { document.getElementById("result").innerHTML+=data.hello + "<br />"; });
send:
//服務器 socket.on('connection', function(client){ client.send('hello, I am the server'); }); //客戶端 socket.on('message',function(data) { document.getElementById("result").innerHTML+=data + "<br />"; });
實例:(socket.io)
客戶端:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style> div{ border-radius: 10px; border: 2px solid pink; width:800px; } </style> </head> <body> <h1></h1> <div id="result"></div> <script src="http://localhost:8000/socket.io/socket.io.js"></script> <script> //創建Socket.IO實例,建立連接 var socket = io.connect('http://localhost:8000'); // 添加一個連接監聽器 socket.on('connect',function() { console.log('Client has connected to the server!'); }); // 添加一個連接監聽器 socket.on('message',function(data) { document.getElementById("result").innerHTML+=data + "<br />"; }); socket.on('emitMessage',function(data) { document.getElementById("result").innerHTML+=data.hello + "<br />"; }); // 添加一個關閉連接的監聽器 socket.on('disconnect',function() { console.log('The client has disconnected!'); }); // 通過Socket發送一條消息到服務器 function sendMessageToServer(message) { socket.send(message); } var date = new Date(); var ms="Time: "+date.toString()+"Today is a nice day, wish you happy"; setInterval("sendMessageToServer(ms)",1000); </script> </body> </html>
服務器:
var http = require("http"); var io= require('socket.io'); var server = http.createServer(function(request, response){ response.writeHead(200,{"Content-Type":"text/html"}); response.write("WebSocket Start~~~~~~~~~~~~"); response.end(""); }).listen(8000); var socket= io.listen(server); // 添加一個連接監聽器 socket.on('connection', function(client){ client.on('message',function(event){ console.log('Received message from client!',event); client.emit('emitMessage', { hello: 'messgge received, wish you happy'+new Date().toString() }); }); client.on('disconnect',function(){ // clearInterval(interval); console.log('Server has disconnected'); }); client.send('hello, I am the server'); });
結果:
客戶端:

服務器端:

相關博文:SSE及相關技術(web sockets, long polling等)
