我正在创建一个应用程序,在我看来,它需要一个可以在任何给定时间在客户端面前显示的变量。
举个例子,用户 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>
关于javascript - Socket.IO Node.JS 客户端显示变量。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602218/