Socket.IO Node.JS客户端显示变量
Socket.IO Node.JS Client Side Displaying Variable.
我正在创建一个应用程序,在我看来,该应用程序需要一个变量,该变量会在任何给定时间显示在客户端面前。
举个例子,用户foo有100美元。发生了一个事件,从用户foo的帐户中扣除20美元。一旦发生这种扣除,我希望客户发短信改为80美元。
我对如何实现这一点有着基本的理解。
这是我的代码,
app.js
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
var balance = '100';
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://192.168.1.50');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
<html><p>Balance: balancehere.</p> </html>
</script>
我可以想象它必须由app.js发出,但我不知道如何向客户端显示它。你可以在index.html中看到,我有我想要显示变量的地方。
你的HTML完全搞砸了,这里有一个工作代码的例子,每次客户端点击"购买",它都会向Node服务器发送一个信号,这个服务器会收到它,从他的余额中扣除20美元,并将更新后的余额发送给客户端。
app.js:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
var balance = '100';
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
console.log('connected');
socket.on('buy', function (data) {
socket.emit('update balance', data-20); // Decrease 20 from the balance
});
socket.emit('news', { hello: 'world' });
});
index.html:
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
window.addEventListener("load", function(event) {
function updateBalance () {
document.getElementById("balance").innerText = balance;
}
var balance = 100;
updateBalance();
var socket = io(location.href.split( '/' )[2]); // Connect to same URL
socket.on('update balance', function (data) {
balance = data;
updateBalance();
});
document.getElementById("button").onclick = function () {
socket.emit('buy', balance);
};
});
</script>
</head>
<body>
<p>Balance: $<span id="balance"></span></p><br/>
<button id="button">Buy</button>
</body>
</html>
我认为index.html
中的套接字应该首先发出connection
。
尝试更改
var socket = io('http://192.168.1.50');
至
var socket = io('http://192.168.1.50');
socket.emit('connection', 'test');
相关文章:
- 单击“JavaScript显示变量”
- Cartodb信息窗口未在地图上显示变量
- 如何更新和显示变量
- 如果项目不匹配,则显示变量
- 在 HTML 中显示变量的好做法是什么?
- 在 Javascript 中,值不来,而是显示变量名称
- 缩短角度显示变量
- 如何使用Tinybox显示变量
- 在不同条件下显示变量的不同值
- console.log() 在变量值实际更改之前显示变量的更改值
- 引导程序引导盒在消息中显示变量
- 仅显示变量内的一段文本
- 我想使用 innerHTML 显示变量的值,但我的代码不起作用
- 使用带有按钮的JS函数来显示变量
- 无法使用车把正确在我的“模板”中显示变量.js
- 选中选择框选项时显示变量
- 如何使用显示变量url的iframe打开引导模式
- 我想显示变量'b[i]'而不是'x[i].childNodes[0].nodeValue'
- 数字框jeasyui没有显示变量中的值
- 如何在AngularJS网站中显示变量的名称