我的实现每次都会抛出一个错误(在chrome和safari中)。根据维基百科,它取决于他们提供的输入输出值here。
我不知道如何进一步调试这个,因为chrome和ff中的错误消息没有提供有关它们失败原因的信息(或者它们是什么?)
服务器 -
var domain = "http://www.mysitee.com/";
domain = "localhost/";
var port = 80;
var fs = require("fs");
var util = require("util");
var http = require("http");
var crypto = require("crypto");
var net = require("net");
var server = http.createServer();
var start = new Date().getTime();
var indexFile = fs.readFileSync(__dirname + "/index.htm");
var opened = new Date().getTime();
indexFile = indexFile.toString() + "\
<!-- read time: " + (opened - start) + "ms --><br/>\r\n\
<!-- index size: " + (indexFile.length / 1024).toFixed(2) + "kb -->";
server.on("upgrade", function (req, socket, upgradeHead) {
var crypto = require("crypto");
var shasum = crypto.createHash("sha1");
shasum.update(req.headers["sec-websocket-key"]);
shasum.update("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
var hash = shasum.digest("hex");
console.log("hex:" + hash);
var myVal = new Buffer(hash, "hex").toString('base64');
console.log("myVal: " + myVal);
socket.setNoDelay(true);
socket.write("\
HTTP/1.1 101 Switching Protocols\r\n\
Upgrade: websocket\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Accept: " + myVal + "\r\n\
Sec-WebSocket-Protocol: chat\r\n\r\n"
);
});
server.on("request", function (req, res) {
if (req.url === "/e")
process.exit();
console.log("request " + indexFile.substring(0, 50));
res.write(indexFile);
res.end();
});
server.on("connection", function () {
console.log("connection");
});
server.on("connect", function () {
console.log("connect");
});
server.on("checkContinue", function () {
console.log("check continue");
});
server.on("close", function () {
console.log("close");
});
server.on("clientError", function (e) {
console.log("client error");
});
server.listen(port);
客户端 -
var connection = new WebSocket("ws:localhost:80");
connection.onopen = function () { alert("OPEN"); };
connection.message = function () { alert("MESSAGE"); };
connection.onerror = function (e) { alert("ERROR"); console.log(e); };
connection.onclose = function () { alert("CLOSE"); };