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 = 'rn';
// 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="layout.css" rel="stylesheet" type="text/css" />
<body><textarea id="output" readonly="readonly"></textarea>
<br>
<textarea id="input"></textarea>
<button id="send">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);










