-
Notifications
You must be signed in to change notification settings - Fork 0
Using Socket IO
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!");
}
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
};
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);
}
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
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 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}
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.
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.
Client clicks any card -> sends the index to the server, which stores the card values of the card.