Server bootstrap.
parent
e3ebee4557
commit
44b411880d
|
|
@ -3,6 +3,7 @@
|
|||
"version": "0.1.0",
|
||||
"description": "A generic WebRTC library and peering server.",
|
||||
"scripts": {
|
||||
"start:server": "node peer-exchange/src/server.js",
|
||||
"test": "jest"
|
||||
},
|
||||
"repository": {
|
||||
|
|
|
|||
|
|
@ -1,71 +1,10 @@
|
|||
const WebSocketServer = require('ws').Server;
|
||||
const Session = require('./models/session');
|
||||
const Client = require('./models/client');
|
||||
const { createId } = require('./random');
|
||||
const {Registry} = require('./models/registry.js');
|
||||
const {createConnectionHandler} = require('./handler.js');
|
||||
|
||||
const PORT = process.env.PORT || 9000;
|
||||
|
||||
const server = new WebSocketServer({port: 9000});
|
||||
|
||||
const sessions = new Map;
|
||||
|
||||
function createClient(conn, id = createId()) {
|
||||
return new Client(conn, id);
|
||||
}
|
||||
|
||||
function createSession(id = createId()) {
|
||||
if (sessions.has(id)) {
|
||||
throw new Error(`Session ${id} already exists`);
|
||||
}
|
||||
|
||||
const session = new Session(id);
|
||||
console.log('Creating session', session);
|
||||
|
||||
sessions.set(id, session);
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
function getSession(id) {
|
||||
return sessions.get(id);
|
||||
}
|
||||
|
||||
server.on('connection', conn => {
|
||||
console.log('Connection established');
|
||||
const client = createClient(conn);
|
||||
|
||||
conn.on('message', msg => {
|
||||
console.log('Message received', msg);
|
||||
const data = JSON.parse(msg);
|
||||
|
||||
if (data.type === 'create-session') {
|
||||
const session = createSession();
|
||||
session.join(client);
|
||||
|
||||
client.send({
|
||||
type: 'session-created',
|
||||
id: session.id,
|
||||
});
|
||||
} else if (data.type === 'join-session') {
|
||||
const session = getSession(data.id) || createSession(data.id);
|
||||
session.join(client);
|
||||
} else {
|
||||
client.broadcast(data);
|
||||
}
|
||||
});
|
||||
|
||||
conn.on('close', () => {
|
||||
console.log('Connection closed');
|
||||
const session = client.session;
|
||||
if (session) {
|
||||
session.leave(client);
|
||||
if (session.clients.size === 0) {
|
||||
sessions.delete(session.id);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(sessions);
|
||||
});
|
||||
});
|
||||
server.on('connection', createConnectionHandler(new Registry()));
|
||||
|
||||
console.log(`Running on port ${PORT}`);
|
||||
|
|
|
|||
Loading…
Reference in New Issue