-
-
Save holtwick/d10baa8123b4b704a86dd052aecf0b70 to your computer and use it in GitHub Desktop.
Super basic socket.io v3 signaling server
This file contains 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
// (C)opyright 2021 Dirk Holtwick, holtwick.it. All rights reserved. | |
import helmet from "helmet" | |
import cors from "cors" | |
const config = { | |
host: process.env.HOST || undefined, | |
port: process.env.PORT || 3000, | |
message: { | |
announce: "announce", | |
publish: "publish", | |
signal: "signal", | |
}, | |
} | |
async function run() { | |
const app = require("express")() | |
app.use(helmet()) | |
app.use(cors()) | |
const http = require("http").createServer(app) | |
const io = require("socket.io")(http, { | |
cors: true, | |
}) | |
io.on("connection", (socket) => { | |
let activeRoom | |
const connSocketID = socket.id | |
// Subscribe to {room} and announce to others, such they can signal us | |
socket.on(config.message.publish, (msg) => { | |
try { | |
const { room, data } = msg | |
activeRoom = room | |
socket.join(room) | |
socket.to(room).emit(config.message.announce, { | |
id: connSocketID, | |
room, | |
data, | |
}) | |
io.to(room) | |
.allSockets() | |
.then((ids) => {}) | |
} catch (error) { | |
console.error(config.message.publish, error, msg) | |
} | |
}) | |
// Send {id, data} to socket.id === id | |
socket.on(config.message.signal, (msg) => { | |
try { | |
const toSocket = io.of("/").sockets.get(msg.id) | |
if (toSocket) { | |
toSocket.emit(config.message.signal, msg) | |
} | |
} catch (error) { | |
console.error(config.message.signal, error, msg) | |
} | |
}) | |
}) | |
http.listen( | |
{ | |
host: config.host, | |
port: config.port, | |
}, | |
() => { | |
const { port, family, address } = http.address() | |
console.info(`Listening on ${address}:${port} (${family})`) | |
} | |
) | |
} | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment