使用socket.io与其他javascript文件nodejs一起发送和获取数据并表达

时间:2013-12-18 14:31:25

标签: javascript node.js sockets express

假设我有一个需要与其他JavaScript文件通信的JavaScript文件。所以我可以在不同的javascript文件中使用这些数据。

在这种情况下,我有game_server.js。在gameserver.js我有两个变量,我想在gamecore.js中使用

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

我想将它们发送到de app.js中的socket.io,然后在game_core.js中使用这些变量。所以我可以获得有关主机和客户端的数据。

在gamecore课程中,我希望有类似的东西

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

这一切都是关于从服务器端向客户端获取信息,最好的方法是通过socket.io,但我真的不知道如何

同样在game_server脚本中有一个游戏实例

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
   };

game_core声明了游戏的实例

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

所以应该可以获得player_hostplayer_client

1 个答案:

答案 0 :(得分:1)

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>