Skip to content

Instantly share code, notes, and snippets.

@hebuliang
Created March 11, 2012 13:20
Show Gist options
  • Save hebuliang/2016462 to your computer and use it in GitHub Desktop.
Save hebuliang/2016462 to your computer and use it in GitHub Desktop.
Simple handshake demo for [RFC 6455]
(function() {
// 注:Firefox 11.0已经去掉了WebSocket对象特有前缀
var ws = new WebSocket('ws://localhost:8888');
ws.onopen = function(e){
// ws.send('Client message!!');
}
ws.onmessage = function(e) {
// TODO
};
ws.onclose = function() {
// TODO
};
})();
/**
* WebSocket服务器测试程序
* Surpport [RFC 6455] only
* I just want a pure WebSocket Server which could run in Nodejs.
* No client code jam, no Hixie or IETF, no flash etc, just for fun!
*/
var util = require("util")
,net = require("net")
,http = require("http")
,crypto = require('crypto')
,buffer = require('buffer')
,PORT = 8888
,CRLF = '\r\n'
,MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
;
function createServer(){
return new WebSocketServer();
};
function WebSocketServer(){
var server = this;
http.Server.call(server);
server.addListener("connection", function(socket){
// TODO requests_recv++;
});
server.addListener("request", function(req, res){
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("okay");
res.end();
});
/**
* Client handshake listener
*/
server.addListener("upgrade", function(req, socket, upgradeHead){
var key = req.headers['sec-websocket-key'];
var shasum = crypto.createHash('sha1');
key = shasum.update(key + MAGIC);
key = shasum.digest('base64');
var respHeaders = [
'HTTP/1.1 101 Switching Protocols'
, 'Upgrade: websocket'
, 'Connection: Upgrade'
, 'Sec-WebSocket-Accept: ' + key
];
// 响应头最后要以2个CRLF结尾[RFC6455]
socket.write(respHeaders.concat('','').join(CRLF));
});
};
/**
* 继承http.Server
* 监听 request|connection|upgrade 事件
*/
util.inherits(WebSocketServer, http.Server);
var server = createServer();
server.listen(PORT, function(){
console.log('server started at port 8888...');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment