websockets介紹
websockets這個新協議爲客戶端提供了一個更快、更有效的通信線路。像HTTP一樣,websockets運行在TCP連接之上,但是它們更快,因爲我們不必每次都打開一個新的連接來發送消息,因爲只要服務器或客戶端想要,連接就會一直保持活躍。
更好的是,由於連接永遠不會中斷,我們終於可以使用全雙工通信,這意味着我們可以將數據推送到客戶機,而不必等待它們從服務器請求數據。這允許數據來回通信,這對於實時聊天應用程序,甚至是遊戲都是非常理想的。
實例
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(1337, '127.0.0.1');
/*
And connect with a tcp client from the command line using netcat, the *nix
utility for reading and writing across tcp/udp network connections. I've only
used it for debugging myself.
$ netcat 127.0.0.1 1337
You should see:
> Echo server
*/
/* Or use this example tcp client written in node.js. (Originated with
example code from
http://www.hacksparrow.com/tcp-socket-programming-in-node-js.html.) */
var net = require('net');
var client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});