V
V
Vladimir2019-05-28 19:01:18
JavaScript
Vladimir, 2019-05-28 19:01:18

How to send data to sender using express-socket.io-session?

Server:

var express = require('express');
var app = express();
var http = require('http').Server(app);
var mysql = require('mysql');
var session = require("express-session")({

    secret'boss',

    resavetrue,

    saveUninitializedtrue,

      maxAge: 25200000

});
var sharedsession = require("express-socket.io-session");

var connections=0,max_connections=5,port = 3000,maxhp=300000,hp=maxhp,x,msg,db;
var max_user_hp = 30000,user_hp,x2,email,nick;

let io = require('socket.io')(http, {
  
});

app.use(express.static(__dirname + '/client')); 
app.use(session);

 

// Use shared session middleware for socket.io

// setting autoSave:true

io.use(sharedsession(session, {

    autoSave:true

})); 




app.get('/', function(req,res) {
  res.sendFile(__dirname + '/client/public/auth.html');
});

app.get('/boss', function(req,res) {
  res.sendFile(__dirname + '/client/public/boss.html');
});

http.listen(port, function() {
  console.log('listening on *:' + port);
});

db = mysql.createConnection({
  host : 'localhost', 
  user : 'root', 
  password : '',
  database : 'game'
});

db.connect((err) => {
  if(err) console.log(err);
  console.log("Mysql connected");
});


io.on('connection', function(socket) {	

      //Контроль подключений	
      //connections+=1;
      io.emit('connections', connections);
      
      console.log('connected client:' + connections);
      
      
      if(connections > max_connections) {
        
        socket.on('forceDisconnect', () => {
            socket.disconnect(true);
            console.log('Server full!' + max_connections + '/' + max_connections);
        });
      }
      
      socket.on( 'disconnect', () => { 
        connections -= 1; 
        console.log( 'client disconnected:' + connections);
        io.emit('connections', connections);
        io.emit('server full', 'Заебал алерт!');
      });
      
      
      //Хп босса
      socket.on('boss fight', function(data) {
          hp = hp-data;
          if(hp<=0) {
            hp = maxhp;
            io.emit('win');						
          }
          x = hp/maxhp*100;
   			io.emit('realtime hp', hp);
   			if(hp>0) io.emit('hp line width', x);
   			if(hp<=0) io.emit('hp line width', 0);
   			if(hp+user_hp <= 0) {
   				io.emit('draw');
   			}
   	});
   	socket.on('hp line for all', function(data) {
          x = hp/maxhp*100;
   			io.emit('realtime hp', hp);
   			io.emit('hp line width', x);
   			if(hp<=0) {
   				io.emit('hp line width', 0);
   				io.emit('win');
   			}
   			if(hp+user_hp <= 0) {
   				io.emit('draw');
   			}
   	});
   	//end
   	
   	
   	//Хп игрока   	
   	socket.on('user fight', function(hpp) {
   		user_hp = hpp;
 
   		if(user_hp<=0) {
   			socket.emit('lose');
   		}
   		if(hp+user_hp <= 0) {
   			socket.emit('draw');
   		}
   	});
   	//end
   		
   		
   	
   	//Чат
   	socket.on('chat message', function(data) {
   		msg = data;
   		io.emit('chat msg',msg);
   	});
   	//end
   	
   	
   	//Блокировка пользователей
   	socket.on('banned', function(data) {
   		var ban = '';
   		if(data == ban) {
   			io.emit('ban', 'Вы забанены!');
   			socket.disconnect(true);
   		}
   	});
   	//end
   	
   	
   	
   	//Регистрация
   	
   	socket.on('email', function(data) {
   		email = data;
   	});
   	socket.on('nick', function(data) {
   		nick = data;
   		console.log(data);
   	});
   	
   	socket.on('query', function(data) {
   		
   		db.query("INSERT INTO players (id,nickname,email) VALUES('','" + nick + "','" + email +  "')", (err,result) => {

     	if(err) console.log(err);

     	console.log("Insert");
  			});
      });

     //end
});

Customer:
var host = 'http://localhost:3000/';
var socket = io(host, {
  transports: ['websocket'], 
  upgrade: false
});
var hp,hp2,connections,x,message,msg,x2;
var boss_damage = Math.floor((Math.random() * 1000) + 500);
var user_damage = Math.floor((Math.random() * 31000) + 1000);
var bonus_sword_damage = 10000;
var max_user_hp = 30000,user_hp = max_user_hp,x2,lose,win,draw;

$.getJSON('https://api.ipify.org?format=json', function(data){ 
  	socket.emit('banned',data.ip); 
});

socket.emit('hp line for all');

var count=25200; 
var counter=setInterval(timer, 1000);
function timer() {
 count--; 
 if (count <= 0 || lose == 'lose' || win == 'win' || draw == 'draw') {
 	 clearInterval(counter);
 	 localStorage.clear();
 	 localStorage.setItem('hp', max_user_hp); 	 
 }
}

socket.on('connect', () => {
  if(user_hp != 0) {
   user_hp = localStorage.getItem('hp');
   x2 = localStorage.getItem('w'); 
  }
});

$('.user-name').click(function() {
  $('.user-name').css({'top':'0px','position':'absolute','z-index':'9999'});
});


$('.chat').click(function() {
  alert('На данный момент чат отключён - попробуйте позже.');
});


      		
$('.boss').click(function() {
    
    user_hp = user_hp-boss_damage;
    x2 = user_hp/max_user_hp*100;
    
    if(user_hp && localStorage.getItem('hp') <= 0) {
      localStorage.setItem('hp', max_user_hp);
      user_hp = max_user_hp;
    }
    
    localStorage.setItem('hp', user_hp);
    localStorage.setItem('w', x2);
    
  socket.emit('boss fight', user_damage);
  socket.emit('user fight', user_hp);
  $('.hp-line').css("width", x+'%');
  $('.user-hp').css("width", x2+'%');
});

$('.sword').click(function() {
   user_hp = user_hp-boss_damage;
  socket.emit('boss fight', user_damage+bonus_sword_damage);
  socket.emit('user fight', user_hp);
  $('.hp-line').css("width", x+'%');
  $('.user-hp').css("width", x2+'%');
});
/*$('.send-to-chat').click(function() {
  name = $(".user-name").val();
  msg = $(".chat-message").val();
  socket.emit('chat message', msg);
});*/

socket.on('realtime hp', function(data) {
  hp = data;
  $('.hp-line').html(hp);
});

$('.hp-line').html(hp);
$('.user-hp').css("width", x2+'%');
      	       	 
socket.on('disconnect', function(data) {
  alert('Вы отключены от сервера!');
 // window.location.replace(host + 'serverfull');
});
socket.on('hp line width', function(data) {
  x = data;
  $('.hp-line').css("width", x+'%');
  $('.user-hp').css("width", x2+'%');
});
socket.on('chat msg', function(data) {
  message = data;
  $(".chat-box").append("<li class='message'><div class='name'></div>" + message + "</li>");
});
socket.on('ban', function(data) {
  alert(data);
});

socket.on('win', function(data) {
  alert('You win this battle!');
  win = 'win';
  //window.location.replace("/");
});

socket.on('lose', function(data) {
  alert('You lose this battle!');
  lose = 'lose';
});

socket.on('server full', function(data) {
  alert(data);
});

socket.on('draw', function(data) {
  alert('DRAW!Revenge!');
  draw = 'draw';
});

window.onbeforeunload = function() { 
  //return "Данные не сохранены. Точно перейти?";
  
};

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question