LRPuno / glory_brawl

Project 1 Game
1 stars 1 forks source link

Learn node JS socket IO #9

Closed Jaybhatt216 closed 6 years ago

Jaybhatt216 commented 6 years ago

This will be backup just in case fire base does not work out for multiplayer

Jaybhatt216 commented 6 years ago

@LRPuno @AngelusQQ @ChristopherEdynak see below the code for basic sockets server side also the add in for the client side the socket is made via express server so this a webserver and socket

//this is the server also in express

//import express
const express = require('express');
//use it in the app variable
const app = express();
//create the server var to go over the internet and then create the server using express
const server = require('http').createServer(app);
//now for socket IO, import socket as it to listen for the server
const io = require('socket.io').listen(server);

// declare arrays for users and connections
users =[];
connections = [];

//run the server with a port 
server.listen(process.env.PORT || 3000);
console.log('server running...');
//create a route right now will be the home page
app.get('/',function(req, res){
    res.sendFile(__dirname + '/index.html');

});

//start sockets an dpush to array
io.sockets.on('connection', function(socket){
    connections.push(socket);
    console.log('connected: %s sockets connected', connections.length);
//disconnect the socket
socket.on('disconnect',function(data){
connections.splice(connections.indexof(socket), 1);
console.log('Disconnected %s sockets connected', connections.length);   

});

});

client side need to add in the script tag for the socket js file and then add the below

<script>
    $(function(){
        var socket = io.connect();

    });