server.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var net = require('net'),
  2. fs = require('fs'),
  3. http = require('http'),
  4. websocket = require('websocket'),
  5. crypto = require('crypto');
  6. config = require('../config');
  7. world = require('../world');
  8. core = require('./core');
  9. WebsocketLogin = require('./websocketlogin');
  10. var logins = [];
  11. try {
  12. core.load();
  13. } catch (error) {
  14. console.error("Server cannot be loaded", error, error.stack);
  15. process.exit(1);
  16. }
  17. var webserver = http.createServer(function(request, response) {
  18. });
  19. webserver.on('error', function(error) {
  20. console.error("Unknown webserver error", error, error.stack);
  21. });
  22. // create the server
  23. var websocketserver = new websocket.server({
  24. httpServer: webserver
  25. });
  26. // WebSocket server
  27. websocketserver.on('request', function(request) {
  28. var connection = request.accept(null, request.origin);
  29. var login = new WebsocketLogin(connection);
  30. logins.push(login);
  31. login.attach();
  32. connection.on('message', function(message) {
  33. if (message.type === 'utf8') {
  34. try {
  35. login.receive(JSON.parse(message.utf8Data));
  36. } catch (error) {
  37. console.error("Unknown webserver error", error, error.stack);
  38. }
  39. } else {
  40. console.log(message);
  41. }
  42. });
  43. connection.on('close', function(connection) {
  44. login.disconnect();
  45. logins.splice(logins.indexOf(login), 1);
  46. });
  47. });
  48. webserver.listen(config.websocketport, config.websocketlisten, function() {
  49. console.log("Websocket server listening on " + config.websocketlisten + ":" + config.websocketport);
  50. });
  51. process.stdin.resume();
  52. process.stdin.setEncoding('utf8');
  53. process.stdin.on('data', function (data) {
  54. var input = data.trim().split(" ");
  55. switch(input.shift()) {
  56. case "exit":
  57. case "quit":
  58. case "stop":
  59. console.log("The server is shutting down");
  60. process.exit(0);
  61. break;
  62. case "flush":
  63. for(var i in session.players) {
  64. session.players[i].logout();
  65. }
  66. session.players = [];
  67. break;
  68. }
  69. });