2021-01-29 02:40:52 +02:00
|
|
|
const constants = require("./constants");
|
2021-02-02 10:17:49 +02:00
|
|
|
const parser = require('./Parser');
|
2021-01-29 02:40:52 +02:00
|
|
|
|
2021-01-26 12:04:53 +02:00
|
|
|
class Socket {
|
|
|
|
constructor({ initialState='CONNECTING', socket }) {
|
|
|
|
this._state = initialState;
|
|
|
|
this._socket = socket;
|
2021-01-29 02:40:52 +02:00
|
|
|
this._accepted = false;
|
|
|
|
this._fateDecided = false; // Wether the decision to accept or reject the socket was made
|
2021-01-26 12:04:53 +02:00
|
|
|
|
|
|
|
this._socket.on('data', (e) => {
|
2021-01-29 02:40:52 +02:00
|
|
|
if (this._state !== constants.states.OPEN) return;
|
|
|
|
|
2021-02-02 10:17:49 +02:00
|
|
|
this._decodePayload(e.buffer);
|
2021-01-26 12:04:53 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-03 02:18:28 +02:00
|
|
|
Socket.prototype.sendText = function(text) {
|
|
|
|
const frame = new parser.WebsocketFrame();
|
|
|
|
frame.FIN = 1;
|
|
|
|
frame.RSVx = 0;
|
|
|
|
frame.Opcode = 0x01;
|
|
|
|
|
|
|
|
frame.MASK = 0;
|
|
|
|
const length = text.length;
|
|
|
|
if (length > 125) {
|
|
|
|
frame.PayloadLen = 126;
|
|
|
|
} else if (length >= 65536) {
|
|
|
|
frame.PayloadLen = 127;
|
|
|
|
} else if (length <= 125) {
|
|
|
|
frame.PayloadLen = length;
|
|
|
|
}
|
|
|
|
frame.PayloadLenEx = length;
|
|
|
|
frame.PayloadData = Buffer.from(text);
|
|
|
|
|
|
|
|
this._socket.write(frame.toBuffer());
|
|
|
|
};
|
|
|
|
|
2021-02-02 10:17:49 +02:00
|
|
|
Socket.prototype._decodePayload = function(payload) {
|
|
|
|
console.log(parser.parseWebsocketFrame(new DataView(payload)));
|
|
|
|
};
|
|
|
|
|
2021-01-29 02:40:52 +02:00
|
|
|
Socket.prototype._setConnectionState = function(state) {
|
|
|
|
this._state = state;
|
|
|
|
};
|
|
|
|
|
|
|
|
Socket.prototype._setAccepted = function(state) {
|
|
|
|
if (this._fateDecided) throw new Error('Tried to decide fate (wether socket is accepted or not) more than 1 time');
|
|
|
|
|
|
|
|
this._fateDecided = true;
|
|
|
|
this._accepted = state;
|
|
|
|
};
|
|
|
|
|
2021-01-26 12:04:53 +02:00
|
|
|
module.exports = Socket;
|