gpt4 book ai didi

javascript - 简单和基本的 Node WebSocket 客户端和服务器示例

转载 作者:行者123 更新时间:2023-11-30 11:45:33 26 4
gpt4 key购买 nike

我正在寻找一个非常基本的 websocket 示例服务器,它可以从套接字进行升级和读取日期。目前我面前有 RFC 6455 并且正在研究它,但有兴趣看看是否有一个简单的示例/源项目可供我查看。

我目前一直在 WS 和 Socket.io 源代码中,但它们有点密集

最佳答案

也许这可以帮助其他人寻找 websocket 服务器的简单示例。这只会读取 126 个字节,并且充满了控制台日志以了解正在发生的事情。我浏览了 RFC 6455 文档以了解如何阅读框架。

  0                   1                   2                   3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+

server.js [Node.js v7.2.1]:

//Require Build In
const http = require('http');
const fs = require('fs');
const crypto = require('crypto');

//My Consts
const hostname = '127.0.0.1';
const port = 3000;
const webSocketMagicString = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';

//Create Server
const server = http.createServer((requestIncoming, responseOutGoing) => {
responseOutGoing.statusCode = 200;
responseOutGoing.setHeader('Contenet-Type', 'text/html');

fs.readFile('index.html', function(error, content){
responseOutGoing.end(content);
});


});

server.listen(port, hostname, () => {
console.log(`Server is online on http://${hostname}:${port}`);
});

server.on('upgrade', (request, socket, head) => {
var secWebSocketKey = request.headers['sec-websocket-key'] + webSocketMagicString;
var hashedKey = crypto.createHash('SHA1').update(secWebSocketKey).digest('base64');

//Send Back to requester
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n'
+ 'Upgrade: WebSocket\r\n'
+ 'Connection : Upgrade\r\n'
+ 'Sec-WebSocket-Accept:'+hashedKey+'\r\n' + '\r\n'
);


//Start Keeping an Eye out for Data
socket.on('data', (data) => {
console.clear();
console.log('Receiving Message:', data);
var isFinished = data[0] & 127;
var optionCode = data[0] & 15;
var isMasked = data[1] >> 7;
var dataLength = data[1] & 127;
console.log('Is Finished: ' + isFinished);
console.log('Is Masked: ' + isMasked);
console.log('Option Code: ' + optionCode);
console.log('Data Length: ' + dataLength);
if(optionCode === 1 && isFinished === 1 && isMasked === 1 && dataLength < 127){
var maskingKey = data.slice(2, 6);
var maskedData = data.slice(6, 6+dataLength);
var unMaskedData = '';
for(var i = 0; i < dataLength; i++){
unMaskedData += String.fromCharCode(maskedData[i] ^ maskingKey[i % 4]);
}
console.log('unMaskedData: ' + unMaskedData);
echoTextMessage(socket, unMaskedData);
}
});
});

function echoTextMessage(socket, str){
var response = [129, str.length];
for(var i = 0; i < str.length; i ++){
response.push(str.charCodeAt(i));
}
console.log(response);
socket.write(new Buffer(response));
}

index.html

<script>
var ws = new WebSocket('ws://127.0.0.1:3000');
ws.onopen = function(){
console.log('Connected to 127.0.0.1:3000!');
}
ws.addEventListener("message", function(event) {
console.log('Received: ' + event.data);
});

sendMessage = (text = 'test') => {
console.log('Sent: ' + text)
ws.send(text);
}
</script>

关于javascript - 简单和基本的 Node WebSocket 客户端和服务器示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41089676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com