使用其他javascript文件nodejs和express发送和获取数据 socket.io

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

本文关键字:获取 数据 socket io express javascript 其他 文件 nodejs      更新时间:2023-09-26

假设我有一个需要与其他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 中的 socket.io.js然后在game_core.js中使用此变量。因此,我可以获得有关主机和客户端的数据。

在游戏核心类中,我希望有这样的东西

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

服务器.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);
});

客户端.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>