Skip to content

Instantly share code, notes, and snippets.

@holtwick

holtwick/signal-server.js Secret

Created Jan 28, 2021
Embed
What would you like to do?
Super basic socket.io v3 signaling server
// (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