我的目的是使用 Node.js + Socket.IO 制作一个聊天应用程序,但我遇到了一个困难。 问题是 minus 事件不能正常工作(结果:64 - 12 = 65),但是 plus 事件工作正常(结果:42 + 23 = 65 ). 也许问题的原因与 socket.once() 函数有关...但我不清楚答案。

以下是我简化的 Node.js 应用程序的源代码。

app.js:

var http = require('http'); 
var fs = require('fs'); 
var socketio = require('socket.io'); 
 
var app = http.createServer(function (req, res) { 
    if (req.url === '/') { 
        fs.readFile(__dirname + '/index.html', function (err, result) { 
            if (err) 
                throw err; 
 
            res.writeHead(200, { 
                'Content-Type': 'text/html' 
            }); 
            res.end(result); 
        }); 
    } else { 
        res.writeHead(404); 
        res.end(); 
    } 
}); 
 
app.listen(3000, function () { 
    console.log('The server running on port 3000.'); 
}); 
 
var io = socketio(app); 
io.on('connection', function (socket) { 
    socket.on('plus', function (param) { 
        socket.emit('result', param.a + param.b); 
    }); 
 
    socket.on('minus', function (param) { 
        socket.emit('result', param.a - param.b); 
    }); 
}); 

index.html:

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
        <meta charset="UTF-8" /> 
        <title></title> 
        <script src="http://cdn.socket.io/socket.io-1.0.6.js"></script> 
        <script> 
            var socket = io(); 
 
            socket.emit('plus', { 
                a: 42, 
                b: 23 
            }); 
 
            socket.once('result', function (result) { 
                var div = document.createElement('div'); 
                div.innerText = '42 + 23 = ' + result; 
                document.body.appendChild(div); 
            }); 
 
            socket.emit('minus', { 
                a: 64, 
                b: 12 
            }); 
 
            socket.once('result', function (result) { 
                var div = document.createElement('div'); 
                div.innerText = '64 - 12 = ' + result; 
                document.body.appendChild(div); 
            }); 
        </script> 
    </head> 
    <body> 
    </body> 
</html> 

结果:

42 + 23 = 65 
64 - 12 = 65 

谢谢。

请您参考如下方法:

因为您同时在“结果”上绑定(bind)了两个事件回调。

<script> 
    var socket = io(); 
 
    socket.emit('plus', { 
        a: 42, 
        b: 23 
    }); 
 
    socket.once('result', function (result,obj) { 
        var div = document.createElement('div'); 
        div.innerText = '42 + 23 = ' + result; 
        document.body.appendChild(div); 
 
        socket.emit('minus', { 
            a: 64, 
            b: 12 
        }); 
        socket.once('result', function (result,obj) { 
            var div = document.createElement('div'); 
            div.innerText = '64 - 12 = ' + result; 
            document.body.appendChild(div); 
        }); 
    }); 
</script> 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

javascript之如何在 Ubuntu 的控制台中设置 slimerjs