const constants = require("./constants"); const parser = require('./Parser'); class Socket { constructor({ initialState='CONNECTING', socket }) { this._state = initialState; this._socket = socket; this._accepted = false; this._fateDecided = false; // Wether the decision to accept or reject the socket was made this._socket.on('data', (e) => { if (this._state !== constants.states.OPEN) return; this._decodePayload(e.buffer); }); } } 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()); }; Socket.prototype._decodePayload = function(payload) { console.log(parser.parseWebsocketFrame(new DataView(payload))); }; 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; }; module.exports = Socket;