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.

69 lines
1.9 KiB

4 years ago
  1. var WebSocket = require('..'),
  2. deflate = require('permessage-deflate'),
  3. fs = require('fs'),
  4. http = require('http'),
  5. https = require('https');
  6. var port = process.argv[2] || 7000,
  7. secure = process.argv[3] === 'tls',
  8. options = {extensions: [deflate], ping: 5};
  9. var upgradeHandler = function(request, socket, head) {
  10. var ws = new WebSocket(request, socket, head, ['irc', 'xmpp'], options);
  11. console.log('[open]', ws.url, ws.version, ws.protocol, request.headers);
  12. ws.pipe(ws);
  13. ws.onclose = function(event) {
  14. console.log('[close]', event.code, event.reason);
  15. ws = null;
  16. };
  17. };
  18. var requestHandler = function(request, response) {
  19. if (!WebSocket.EventSource.isEventSource(request))
  20. return staticHandler(request, response);
  21. var es = new WebSocket.EventSource(request, response),
  22. time = parseInt(es.lastEventId, 10) || 0;
  23. console.log('[open]', es.url, es.lastEventId);
  24. var loop = setInterval(function() {
  25. time += 1;
  26. es.send('Time: ' + time);
  27. setTimeout(function() {
  28. if (es) es.send('Update!!', {event: 'update', id: time});
  29. }, 1000);
  30. }, 2000);
  31. fs.createReadStream(__dirname + '/haproxy.conf').pipe(es, {end: false});
  32. es.onclose = function() {
  33. clearInterval(loop);
  34. console.log('[close]', es.url);
  35. es = null;
  36. };
  37. };
  38. var staticHandler = function(request, response) {
  39. var path = request.url;
  40. fs.readFile(__dirname + path, function(err, content) {
  41. var status = err ? 404 : 200;
  42. response.writeHead(status, {'Content-Type': 'text/html'});
  43. response.write(content || 'Not found');
  44. response.end();
  45. });
  46. };
  47. var server = secure
  48. ? https.createServer({
  49. key: fs.readFileSync(__dirname + '/../spec/server.key'),
  50. cert: fs.readFileSync(__dirname + '/../spec/server.crt')
  51. })
  52. : http.createServer();
  53. server.on('request', requestHandler);
  54. server.on('upgrade', upgradeHandler);
  55. server.listen(port);