You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.4 KiB

4 years ago
  1. var express = require('express');
  2. var sockjs = require('sockjs');
  3. var websocket_multiplex = require('websocket-multiplex');
  4. // 1. Setup SockJS server
  5. var sockjs_opts = {sockjs_url: "http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"};
  6. var service = sockjs.createServer(sockjs_opts);
  7. // 2. Setup multiplexing
  8. var multiplexer = new websocket_multiplex.MultiplexServer(service);
  9. var ann = multiplexer.registerChannel('ann');
  10. ann.on('connection', function(conn) {
  11. conn.write('Ann says hi!');
  12. conn.on('data', function(data) {
  13. conn.write('Ann nods: ' + data);
  14. });
  15. });
  16. var bob = multiplexer.registerChannel('bob');
  17. bob.on('connection', function(conn) {
  18. conn.write('Bob doesn\'t agree.');
  19. conn.on('data', function(data) {
  20. conn.write('Bob says no to: ' + data);
  21. });
  22. });
  23. var carl = multiplexer.registerChannel('carl');
  24. carl.on('connection', function(conn) {
  25. conn.write('Carl says goodbye!');
  26. // Explicitly cancel connection
  27. conn.end();
  28. });
  29. // 3. Express server
  30. var app = express.createServer();
  31. service.installHandlers(app, {prefix:'/multiplex'});
  32. console.log(' [*] Listening on 0.0.0.0:9999' );
  33. app.listen(9999, '0.0.0.0');
  34. app.get('/', function (req, res) {
  35. res.sendfile(__dirname + '/index.html');
  36. });
  37. app.get('/multiplex.js', function (req, res) {
  38. res.sendfile(__dirname + '/multiplex.js');
  39. });