Skip to content

Instantly share code, notes, and snippets.

@holtwick
Created January 28, 2021 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holtwick/d10baa8123b4b704a86dd052aecf0b70 to your computer and use it in GitHub Desktop.
Save holtwick/d10baa8123b4b704a86dd052aecf0b70 to your computer and use it in GitHub Desktop.
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