简体   繁体   中英

Send and get data with socket.io with an other javascript file nodejs and express

Lets say I have a JavaScript file that needs to communicate with other JavaScript file. So I could use this data in different javascript file.

In this case I have a game_server.js . In the gameserver.js I have two variables which I would like to use in the gamecore.js

var host // host of the game
var client // client that had joined the game

I would like to send them to the socket.io in de app.js and then use this variables in the game_core.js . So I can have data about the host and the client.

In the gamecore class i would like to have something like this

game_core.prototype.getPlayerInformation = function(data) {
    this.host = data.host
    this.client = data.client
}

It is all about getting information from the serverside to the clientside and the best way to do it is trough socket.io but i really don't know how

Also in the game_server script there is a instance for a game

game_server.createGame = function(player) {

   //Create a new game instance
   var thegame = {
       id : UUID(),                //generate a new id for the game
       player_host:player,         //so we know who initiated the game
       player_client:null,         //nobody else joined yet, since its new
       player_count:1              //for simple checking of state
   };

In the game_core the instance of a game is declared

var game_core = function(game_instance) {
    //Store the instance, if any
    this.instance = game_instance;
}

So it should be possible to get the player_host and player_client ?

server.js

var app = require('express')()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

server.listen(80);

var Game_core = function(){}
Game_core.prototype.getPlayerInformation = function(data)
{
  this.host = data.host
  this.client = data.client
  return {host: this.host, client: this.client}
}

var game_core = new Game_core()

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

  socket.emit('login', game_core.getPlayerInformation);

});

client.js

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('login', function(data){
     console.log(data); // {host: xx, client: xx}
  })

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM