使用socket.io和其他javascript文件nodejs和express发送和获取数据
假设我有一个JavaScript文件,需要与其他JavaScript文件通信。所以我可以在不同的javascript文件中使用这些数据 在本例中,我有一个使用socket.io和其他javascript文件nodejs和express发送和获取数据,javascript,node.js,sockets,express,Javascript,Node.js,Sockets,Express,假设我有一个JavaScript文件,需要与其他JavaScript文件通信。所以我可以在不同的javascript文件中使用这些数据 在本例中,我有一个game\u server.js。在gameserver.js中,我有两个变量,我想在gamecore.js 我想将它们发送到de app.js中的socket.io,然后在game_core.js中使用这些变量。这样我就可以得到关于主机和客户端的数据 在gamecore类中,我想要这样的东西 这都是关于从服务器端到客户端获取信息的,最好的
game\u server.js
。在gameserver.js
中,我有两个变量,我想在gamecore.js
我想将它们发送到de app.js中的socket.io,然后在game_core.js
中使用这些变量。这样我就可以得到关于主机和客户端的数据
在gamecore类中,我想要这样的东西
这都是关于从服务器端到客户端获取信息的,最好的方法是通过socket.io,但我真的不知道如何实现
在game_服务器脚本中还有一个游戏实例
game_server.createGame=函数(玩家){
在game\u core
中声明游戏实例
因此,应该可以获取player\u主机
和player\u客户端
?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>
var socket=io.connect('http://localhost');
socket.on('login',函数(数据){
console.log(数据);//{host:xx,client:xx}
})
I get everytime undefined这不是因为我没有从game_server.jsneccesary数据中获取必要的数据吗?你能获取其他数据吗?或者什么都没有。我认为与game_客户端建立连接是关键。
//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
};
var game_core = function(game_instance) {
//Store the instance, if any
this.instance = game_instance;
}
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);
});
<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>