我正在为 web 套接字而不是 socket.io 等编写自己的实现。
我的握手很好,但是当客户端发送到服务器时,我不知道如何将这些数据变成有用的东西。它是一个对象吗?它是一个字符串吗?文档说它是 V8 堆外的原始内存位置数组。...?
功能示例(客户端是硬编码字符串)
var http = require("http");
var crypto = require("crypto");
var server = http.createServer();
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");
var myVal = new Buffer(hash, "hex").toString('base64');
var head = "";
head += "HTTP/1.1 101 Switching Protocols\r\n";
head += "Connection: Upgrade\r\n";
head += "Upgrade: WebSocket\r\n";
head += "Sec-WebSocket-Accept: " + myVal + "\r\n\r\n";
socket.setEncoding("utf8");
socket.write(head);
socket.ondata = function (data, start, end) {
var data = data.toString("utf8", start, end);
console.log(" start: " + start + "\n end: " + end + "\n data: " + data);
};
});
server.on("request", function (req, res) {
if (req.url === "/e")
process.exit();
if (req.url.indexOf("favicon") !== -1)
return;
var html = "\
<!DOCTYPE html>\r\n\
<html>\r\n\
<head>\r\n\
<script>\r\n\
var connection = new WebSocket('ws:localhost:80');\r\n\
connection.onopen = function () {\r\n\
console.log('OPEN SUCCESS');\r\n\
connection.send('I am a message from the client.');\r\n\
};\
connection.onmessage = function(msg) {\r\n\
console.log(msg);\r\n\
}\r\n\
connection.onerror = function (e) { console.log('ERROR'); console.log(e); };\r\n\
connection.onclose = function (e) { console.log('CLOSE'); console.log(e);};\r\n\
</script>\r\n\
</head>\r\n\
</html>";
res.writeHead(200, { "Content-Type": "text/html" });
res.write(html);
res.end();
});
server.listen(80);