我正在尝试访问网页以使用 websockets 与 node.js 进行通信。我已经尝试了几个小时,但根本不知道出了什么问题。
服务器
var net = require('net');
var server = net.createServer(function (socket) {
var handsShaked=false;
socket.on('data', function(data) {
if(!handsShaked){
data=(data+"").split("\r").join("").split("\n");
var key=null;
for(i in data){
if(data[i].indexOf("Sec-WebSocket-Key:")===0)
key=data[i].split(":")[1].split(" ").join("");
}
var magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
var sha = sha1(key+magic);
var accept = new Buffer(sha).toString('base64');
socket.write(
"HTTP/1.1 101 Switching Protocols\r\n"+
"Upgrade: websocket\r\n"+
"Connection: Upgrade\r\n"+
"Sec-WebSocket-Accept: "+accept+"\r\n"
);
handsShaked=true;
}
socket.write("test");
});
});
server.listen(10666);
客户
socket = new WebSocket("ws://localhost:10666");
socket.onopen=function(){
console.log('open');
socket.send('Dit is een test');
}
socket.onmessage=function(msg){
console.log('msg');
alert(msg);
}
socket.onerror = function (error) {
console.log('error');
alert('WebSocket Error ' + error);
};
任何人都知道为什么它不工作?