2015-11-09 83 views
0

我正在创建一个应用程序,这个应用程序在我眼中需要一个在任何给定时间都会在客户端前显示的变量。Socket.IO Node.JS客户端显示变量。

举个例子,用户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中看到,我有我想要显示的变量。

回答

2

您HTML完全搞砸了,这里是工作的代码示例,每个客户端点击“购买”时,它会发送向节点服务器发出一个信号,这个人会收到它,从他的余额中折扣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> 
0

我认为插座index.html应该首先发出connection

试图改变

var socket = io('http://192.168.1.50'); 

var socket = io('http://192.168.1.50'); 
socket.emit('connection', 'test');