signaling-server.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. const respond = (code, data, contentType = 'text/plain') => {
  26. res.writeHead(code, {
  27. 'Content-Type' : contentType,
  28. 'Access-Control-Allow-Origin' : '*',
  29. });
  30. res.end(data);
  31. };
  32. respond(404, 'Not Found');
  33. });
  34. const wsServer = new websocket.server({httpServer});
  35. wsServer.on('request', (req) => {
  36. console.log(`WS ${req.resource}`);
  37. const {path} = req.resourceURL;
  38. const splitted = path.split('/');
  39. splitted.shift();
  40. const id = splitted[0];
  41. const conn = req.accept(null, req.origin);
  42. conn.on('message', (data) => {
  43. if (data.type === 'utf8') {
  44. console.log(`Client ${id} << ${data.utf8Data}`);
  45. const message = JSON.parse(data.utf8Data);
  46. const destId = message.id;
  47. const dest = clients[destId];
  48. if (dest) {
  49. message.id = id;
  50. const data = JSON.stringify(message);
  51. console.log(`Client ${destId} >> ${data}`);
  52. dest.send(data);
  53. } else {
  54. console.error(`Client ${destId} not found`);
  55. }
  56. }
  57. });
  58. conn.on('close', () => {
  59. delete clients[id];
  60. console.error(`Client ${id} disconnected`);
  61. });
  62. clients[id] = conn;
  63. });
  64. const endpoint = process.env.PORT || '8000';
  65. const splitted = endpoint.split(':');
  66. const port = splitted.pop();
  67. const hostname = splitted.join(':') || '127.0.0.1';
  68. httpServer.listen(port, hostname,
  69. () => { console.log(`Server listening on ${hostname}:${port}`); });