Created
August 3, 2022 16:05
-
-
Save apacheli/fe5e426f88d7bda3a82183f24315505f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { randomBytes } from "node:crypto"; | |
import { request as httpRequest } from "node:http"; | |
import { request as httpsRequest } from "node:https"; | |
const DEFAULT_PORT = 443; | |
const SEC_WEBSOCKET_VERSION = 13; | |
class WebSocket extends EventTarget { | |
constructor(url, protocols) { | |
super(); | |
this.protocol = protocols; | |
this.url = url; | |
this.#connect(); | |
} | |
static { | |
this.CONNECTING = this.prototype.CONNECTING = 0; | |
this.OPEN = this.prototype.OPEN = 1; | |
this.CLOSING = this.prototype.CLOSING = 2; | |
this.CLOSED = this.prototype.CLOSED = 3; | |
} | |
#connect() { | |
const url = new URL(this.url); | |
const isSecure = url.protocol === "wss:" || url.protocol === "https:"; | |
const request = isSecure ? httpsRequest : httpRequest; | |
const headers = { | |
"Connection": "Upgrade", | |
"Sec-WebSocket-Key": randomBytes(16).toString("base64"), | |
"Sec-WebSocket-Version": SEC_WEBSOCKET_VERSION, | |
"Upgrade": "websocket", | |
}; | |
const req = request({ | |
defaultPort: DEFAULT_PORT, | |
port: url.port ?? DEFAULT_PORT, | |
headers, | |
host: url.host, | |
path: url.pathname + url.search, | |
}); | |
req.end(); | |
req.on("upgrade", (_, socket) => { | |
// socket.setEncoding("utf8"); | |
socket.on("data", (data) => { | |
const [a, b] = data; | |
const fin = a & 0x80; | |
const rsv1 = a & 0x40; | |
const rsv2 = a & 0x20; | |
const rsv3 = a & 0x10; | |
const opcode = a & 0x0F; | |
const mask = b & 0x80; | |
const payloadLen = b & 0x7F; | |
}); | |
}); | |
} | |
} | |
new WebSocket("wss://gateway.discord.gg"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment