使用其他javascript文件nodejs和express发送和获取数据 socket.io
Send and get data with socket.io with an other javascript file nodejs and 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 中的 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_host
和player_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>
相关文章:
- Ajax-如何获取数据
- 从键值结构中获取数据,并将其与AngularJS中ng重复的值进行比较
- 从数据库中获取数据并插入JavaScript变量
- 从单击的行上的列中获取数据
- Solr查询以按日期月份获取数据&年
- React路由器服务器端渲染和ajax获取数据
- 使用JavaScript在IE9中获取数据列表选项
- 从json子数组获取数据
- 使用angularjs中的rest调用通过id获取数据
- 正在从ruby应用程序中的数据库中获取数据
- 如何从servlet获取数据到ajax成功
- 从选择下拉菜单中获取数据
- 异步获取数据使用JavaScript同步获取数据
- 从服务器获取数据并在选择控件中使用ng选项无法显示选项
- 如何在Angular.js中循环动态添加Fields并获取数据并将其发送到服务器
- JavaScript-获取数据属性的值返回未定义的值
- 如何从文本区域获取数据并使用javascript进行解密
- 在put方法之前从作用域获取数据
- 事件循环的MEAN.JS setInterval进程(从另一个服务器获取数据)
- 使用ReactJS和Flux架构从服务器获取数据的正确方法是什么