Skip to content

Instantly share code, notes, and snippets.

@gtk2k
Created February 20, 2021 11:40
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 gtk2k/6c2d048d0441e1eab387c7093cc22412 to your computer and use it in GitHub Desktop.
Save gtk2k/6c2d048d0441e1eab387c7093cc22412 to your computer and use it in GitHub Desktop.
Simple Room SIgnaling Server
// const ws = new WebSocket('ws://localhost:8998?room=hoge'); でhogeルームに「接続」
// { "join": [peerId] } でhogeルームに「入室」
// { "leave": [peerId] } で「退室」
import WebSocket from 'ws';
import url from 'url';
const connections = {};
const wss = new WebSocket.Server({ port: 8998 });
wss.on('connection', (ws, req) => {
const roomId = url.parse(req.url, true).query.room;
connections[roomId] = connections[roomId] || {};
ws.roomId = roomId;
ws.on('message', (data, req) => {
if (typeof data === 'string') { // text data
const msg = JSON.parse(data);
const roomId = ws.roomId;
if(msg.join) {
ws.peerId = msg.join;
console.log(`join:${ws.peerId}`);
connections[roomId][ws.peerId] = ws;
}
if (msg.join || msg.leave) {
wss.clients.forEach(_ws => {
if (ws !== _ws && _ws.readyState === WebSocket.OPEN) {
ws._socket.send(msg);
}
});
} else {
if(connections[roomId][msg.dst])
connections[roomId][msg.dst].send(msg);
}
console.log(msg);
} else { // binary data
}
});
ws.on('close', _ => {
delete connections[ws.roomId][ws.peerId];
if(!Object.keys(connections[ws.roomId]).length)
delete connections[ws.roomId];
delete ws.roomId;
delete ws.peerId;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment