我正在寻找一个非常基本的websocket示例服务器,可以从套接字执行升级和读取日期。目前我在我面前有RFC 6455并且正在浏览它但是有兴趣看看是否有一个我可以看到的简单示例/源项目。
我目前一直在使用WS和Socket.io源,但它们相当密集
答案 0 :(得分:2)
也许这可能会帮助其他人寻找一个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>