Skip to content

Instantly share code, notes, and snippets.

@bookercodes
Last active November 27, 2023 23:04
Show Gist options
  • Save bookercodes/c9cc54233664cd3c9f5dbcd88c74f0cd to your computer and use it in GitHub Desktop.
Save bookercodes/c9cc54233664cd3c9f5dbcd88c74f0cd to your computer and use it in GitHub Desktop.
import { createServer } from 'http'
import { WebSocketServer } from 'ws'
import { parse } from 'url'
const PORT = 8000
const server = createServer()
// noSever: Tells WebSocketServer not to create an HTTP server
// but to instead handle upgrade requests from the existing
// server (above).
const wsServer = new WebSocketServer({ noServer: true })
const authenticate = request => {
const { token } = parse(request.url, true).query
// TODO: Actually authenticate token
if (token === "abc") {
return true
}
}
server.on('upgrade', (request, socket, head) => {
const authed = authenticate(request)
if (!authed) {
// \r\n\r\n: These are control characters used in HTTP to
// denote the end of the HTTP headers section.
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n')
socket.destroy()
return
}
wsServer.handleUpgrade(request, socket, head, connection => {
// Manually emit the 'connection' event on a WebSocket
// server (we subscribe to this event below).
wsServer.emit('connection', connection, request)
})
})
wsServer.on('connection', connection => {
console.log('connection')
connection.on('message', bytes => {
// %s: Convert the bytes (buffer) into a string using
// utf-8 encoding.
console.log('received %s', bytes)
})
})
server.listen(PORT, () => console.log(`Server started on port ${PORT}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment