signaling-server.js 2.3 KB

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