Advertisement
Blackthorn

Server.js (Ping!)

Feb 21st, 2014
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var util = require("util"),
  2.     io = require("socket.io");
  3.  
  4. var socket, // We'll save the socket object here (see init)
  5.     players, // I say players because I plan on making this into a small game
  6.     events; // Keep track of events
  7.  
  8. // Setup the server //
  9. function init() {
  10.     players = [];
  11.     events = 0;
  12.     socket = io.listen(8000); // Start listening for connections
  13.     socket.configure(function() {
  14.         socket.set("transports", ["websocket"]); // Only websockets for now
  15.         socket.set("log level", 2);
  16.     });
  17.     setEventHandlers();
  18. };
  19.  
  20. // Set event handlers //
  21. function setEventHandlers() {
  22.     socket.sockets.on("connection", onSocketConnection);
  23. }
  24.  
  25. // Do this each time a client connects //
  26. function onSocketConnection(client) {
  27.     util.log("Connection: "+client.id);
  28.     players.push(client);
  29.     client.on("disconnect", onClientDisconnect);
  30.     client.on("ping", onClientPing);
  31.     client.on("goodbye", onPart);
  32.     client.on("msg", onMessage);
  33.     client.on("evenOdd", checkEvenOdd);
  34. };
  35.  
  36. function onClientPing(data) {
  37.     events++;
  38.     this.emit('pong', { // Send a reply to the ping; include some server data.
  39.         message: 'This message came from Node.js',
  40.         uptime: process.uptime(),
  41.         players: Object.keys(socket.connected),
  42.         connected: Object.keys(socket.connected).length,
  43.         numEvents:events});
  44.     util.log("Ping!" );
  45.     if(data) util.log(data);
  46. }
  47.  
  48. function onClientDisconnect(client) {
  49.     events++;
  50.     players.splice(players.indexOf(client.id),1);
  51.     util.log("Player has disconnected: "+this.id);
  52. };
  53.  
  54. function onPart(data){
  55.     events++;
  56.     this.disconnect();
  57.     util.log("Goodbye!");
  58.     if(data) util.log(data);
  59. }
  60.  
  61. function onClientDisconnect() {
  62.     events++;
  63.     util.log("Player has disconnected: "+this.id);
  64. };
  65.  
  66. function onMessage(msg, next) {
  67.     events++;
  68.     if (next) next(msg+"?!?");
  69. };
  70.  
  71. function checkEvenOdd(input, ack) {
  72.     events++;
  73.     if(isNaN(input)){
  74.         ack('Not a number.');
  75.     } else if (+input % 2 === 0) {
  76.         ack('even');
  77.     } else {
  78.         ack('odd');
  79.     }
  80. };
  81.  
  82. init();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement