基于node实现websocket协议

一、协议
WebSocket是一种基于TCP之上的客户端与服务器全双工通讯的协议,它在HTML5中被定义,也是新一代webapp的基础规范之一。

它突破了早先的AJAX的限制,关键在于实时性,服务器可以主动推送内容 到客户端!可能的应用有:多人在线游戏,即时聊天,实时监控,远程桌面,新闻服务器等等。

对于我自己,当前最想尝试的是canvas+websocket组合起来能做什么。

二、实现
由于握手的过程是一个标准的HTTP请求,因此 websocket 的实现有两种选择:1)TCP上实现; 2) 现有HTTP软件上实现。后者的优势在于可以共用现有的HTTP服务器端口,并且不用重新实现认证功能和解析HTTP请求的功能。

这个示例中使用的 node 的HTTP模块。(TCP版及所有文件见 附件)

1、node服务器端代码:

var http = require('http'); var url = require('url'); // var mime = require('mime'); var crypto = require('crypto'); var port = 4400; var server = http.createServer(); server.listen(port,function() { console.log('server is running on localhost:',port); server .on('connection',function(s) { console.log('on connection ',s); }) .on('request',onrequest) .on('upgrade',onupgrade); }); var onrequest = function(req,res) { console.log( Object.keys(req) ,req.url,req['upgrade']); if( !req.upgrade ){ // 非upgrade请求选择:中断或提供普通网页 res.writeHead(200, { 'content-type': 'text/plain' }); res.write( 'WebSocket server works!' ); } res.end(); return; }; var onupgrade = function (req,sock,head) { // console.log('方法:',Object.keys(sock)); if(req.headers.upgrade !== 'WebSocket'){ console.warn('非法连接'); sock.end(); return; } bind_sock_event(sock); try{ handshake(req,sock,head); }catch(e){ console.error(e); sock.end(); } }; // 包装将要发送的帧 var wrap = function(data) { var fa = 0x00, fe = 0xff, data = data.toString() len = 2+Buffer.byteLength(data), buff = new Buffer(len); buff[0] = fa; buff.write(data,1); buff[len-1] = fe; return buff; } // 解开接收到的帧 var unwrap = function(data) { return data.slice(1,data.length-1); } var bind_sock_event = function(sock) { sock .on('data',function(buffer) { var data = unwrap(buffer); console.log('socket receive data : ',buffer,data,'\n>>> '+data); // send('hello html5,'+Date.now()) sock.emit('send',data); }) .on('close',function() { console.log('socket close'); }) .on('end',function() { console.log('socket end'); }) .on('send',function(data) { //自定义事件 sock.write(wrap(data),'binary'); }) }; var get_part = function(key) { var empty = '', spaces = key.replace(/\S/g,empty).length, part = key.replace(/\D/g,empty); if(!spaces) throw {message:'Wrong key: '+key,name:'HandshakeError'} return get_big_endian(part / spaces); } var get_big_endian = function(n) { return String.fromCharCode.apply(null,[3,2,1,0].map(function(i) { return n >> 8*i & 0xff })) } var challenge = function(key1,key2,head) { var sum = get_part(key1) + get_part(key2) + head.toString('binary'); return crypto.createHash('md5').update(sum).digest('binary'); } var handshake = function(req,sock,head) { var output = [],h = req.headers, br = '\r\n'; // header output.push( 'HTTP/1.1 101 WebSocket Protocol Handshake','Upgrade: WebSocket','Connection: Upgrade', 'Sec-WebSocket-Origin: ' + h.origin, 'Sec-WebSocket-Location: ws://' + h.host + req.url, 'Sec-WebSocket-Protocol: my-custom-chat-protocol'+br ); // body var c = challenge(h['sec-websocket-key1'],h['sec-websocket-key2'],head); output.push(c); sock.write(output.join(br),'binary'); }

2、浏览器客户端代码:

<html> <head> <title>WebSocket Demo</title> </head> <style type="text/css"> textarea{width:400px;height:150px;display:block;overflow-y:scroll;} #output{width:600px;height:400px;background:whiteSmoke;padding:1em .5em;color:#000;border:none;} button{padding:.2em 1em;} </style> <link href="https://www.jb51.net/layout.css" type="text/css" /> <body> <textarea readonly="readonly"></textarea> <br> <textarea></textarea> <button>send</button> <script type="text/javascript"> // localhost var socket = new WebSocket('ws://192.168.144.131:4400/') socket.onopen = function(e) { log(e.type); socket.send('hello node'); } socket.onclose = function(e) { log(e.type); } socket.onmessage = function(e) { log('receive @ '+ new Date().toLocaleTimeString() +'\n'+e.data); output.scrollTop = output.scrollHeight } socket.onclose = function(e) { log(e.type); } socket.addEventListener('close',function() { log('a another close event handler..'); },false); // dom var id = function(id) { return document.getElementById(id); } var output = id('output'), input = id('input'), send = id('send'); var log = function(msg) { output.textContent += '> '+msg + '\n' } send.addEventListener('click',function() { socket.send(input.value); },false); </script> </body> </html>

三、细节
在 http 协议之上的 websocket 协议实现只有两步:握手,发送数据。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgyydg.html