signaling-server.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * libdatachannel example web server
  3. * Copyright (C) 2020 Lara Mackey
  4. * Copyright (C) 2020 Paul-Louis Ageneau
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. const fs = require('fs');
  20. const http = require('http');
  21. const websocket = require('websocket');
  22. const clients = {};
  23. const httpServer = http.createServer((req, res) => {
  24. console.log(`${req.method.toUpperCase()} ${req.url}`);
  25. });
  26. const wsServer = new websocket.server({ httpServer });
  27. wsServer.on('request', (req) => {
  28. console.log(`WS ${req.resource}`);
  29. const { path } = req.resourceURL;
  30. const splitted = path.split('/');
  31. splitted.shift();
  32. const id = splitted[0];
  33. const conn = req.accept(null, req.origin);
  34. conn.on('message', (data) => {
  35. if(data.type === 'utf8') {
  36. console.log(`Client ${id} << ${data.utf8Data}`);
  37. const message = JSON.parse(data.utf8Data);
  38. const destId = message.id;
  39. const dest = clients[destId];
  40. if(dest) {
  41. message.id = id;
  42. const data = JSON.stringify(message);
  43. console.log(`Client ${destId} >> ${data}`);
  44. dest.send(data);
  45. }
  46. else {
  47. console.error(`Client ${destId} not found`);
  48. }
  49. }
  50. });
  51. conn.on('close', () => {
  52. delete clients[id];
  53. console.error(`Client ${id} disconnected`);
  54. });
  55. clients[id] = conn;
  56. });
  57. const endpoint = process.env.PORT || '8000';
  58. const splitted = endpoint.split(':');
  59. const port = splitted.pop();
  60. const hostname = splitted.join(':') || '127.0.0.1';
  61. httpServer.listen(port, hostname, () => {
  62. console.log(`Server listening on ${hostname}:${port}`);
  63. });