Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var util = require("util"),
- io = require("socket.io");
- var socket, // We'll save the socket object here (see init)
- players, // I say players because I plan on making this into a small game
- events; // Keep track of events
- // Setup the server //
- function init() {
- players = [];
- events = 0;
- socket = io.listen(8000); // Start listening for connections
- socket.configure(function() {
- socket.set("transports", ["websocket"]); // Only websockets for now
- socket.set("log level", 2);
- });
- setEventHandlers();
- };
- // Set event handlers //
- function setEventHandlers() {
- socket.sockets.on("connection", onSocketConnection);
- }
- // Do this each time a client connects //
- function onSocketConnection(client) {
- util.log("Connection: "+client.id);
- players.push(client);
- client.on("disconnect", onClientDisconnect);
- client.on("ping", onClientPing);
- client.on("goodbye", onPart);
- client.on("msg", onMessage);
- client.on("evenOdd", checkEvenOdd);
- };
- function onClientPing(data) {
- events++;
- this.emit('pong', { // Send a reply to the ping; include some server data.
- message: 'This message came from Node.js',
- uptime: process.uptime(),
- players: Object.keys(socket.connected),
- connected: Object.keys(socket.connected).length,
- numEvents:events});
- util.log("Ping!" );
- if(data) util.log(data);
- }
- function onClientDisconnect(client) {
- events++;
- players.splice(players.indexOf(client.id),1);
- util.log("Player has disconnected: "+this.id);
- };
- function onPart(data){
- events++;
- this.disconnect();
- util.log("Goodbye!");
- if(data) util.log(data);
- }
- function onClientDisconnect() {
- events++;
- util.log("Player has disconnected: "+this.id);
- };
- function onMessage(msg, next) {
- events++;
- if (next) next(msg+"?!?");
- };
- function checkEvenOdd(input, ack) {
- events++;
- if(isNaN(input)){
- ack('Not a number.');
- } else if (+input % 2 === 0) {
- ack('even');
- } else {
- ack('odd');
- }
- };
- init();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement