Skip to content

Using Socket IO

odoland edited this page Nov 16, 2018 · 1 revision

Server-side code:


1) Setting up the sockets

Import Dependencies

const express = require("express");
var http = require("http");`
var socketIO = require("socket.io"); 

Initialize socket IO with server

const app = express();
var server = http.Server(app);
const io = socketIO(server); 

Start the server listening on port 8000

server.listen( 8000, function() {     
console.log("Server started!");
}

2) socket.on and socket.emit

Here, we just put stuff that handles a connection: To handle receiving:

socket.on("name_of_data", function (data) {  
    var proccessed_data = do_something_Function(data);
    socket.emit("new_data", processed_data); // Emit processed data back to client
};

Client side code


1) Starting socket on client and receiving from server:

var socket = io(); 

socket.on("new_data", function (data) { 
     console.log("Received data from the server! + data");
     var processed_data = some_processor_function(data);
     socket.emit("back_to_server", data);
}

2) Where to put this socket.on and socket.emit?

On the server: put them within the 'connection'

io.on('connection', newConnection); 

function newConnection(socket) {
    
    socket.on('cardPlayed', function broadcastCard(data) {
        // This function broadcasts the card to everyone 
        console.log('Received' + data.cardid + ' from: ' + data.username);
        socket.broadcast.emit('cardPlayed', data); // broadcast.emit will emit to ALL clients except the sender
    });  

More ways to use emit: Socket IO Emit Cheatsheet

How it Works

This is a single web-page application built with Node.js, Express, MongoDB and SocketIO. Each section has a div / section which is changed in the css to display (or hide)

Login & Registration

Login and Registration is done by connecting to a MongoDB NoSQL database hosted at mlabs.

Lobby is refreshed to print out all the online players in the lobby. Upon connection, players are added onto . Each socket.id becomes the key, and their username is a value.

var totalOnlinePlayers = {}; // {socket.id:username}

Lobby

The Lobby chatroom sends the client's message to the server. The server receives it through:

socket.on('updateChatbox', (message, sender) => updateChatbox(socket, message, sender));

which will broadcast the message to all other clients to update the HTML (client side) to display the chat message.

Custom Cards Page & Cards

Card values and text are stored in .txt files on the server, under the Classes/ directory.

Classes/promptcards.txt
Classes/playercards.txt
Classes/array.txt

They hold the player's custom cards and the default and player cards.

Game Logic

Client clicks any card -> sends the index to the server, which stores the card values of the card.

Clone this wiki locally