I have got a very basic example. This question has been asked previously multiple times in stack overflow itself but I could not get the right answer so I am going with this basic example.
Server:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.on('chat', function (data) {
var op = false;
if( data.id == '1234' ){
op = 'yes';
}else{
op = 'no';
}
socket.emit('result', { hello: op });
});
});
Client:
<html>
<body>
<button onclick="check()">Test Me :-)</button>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
var check = function(){
var data = { id : '234'};
socket.emit('chat', data);
socket.on('result', function(data){
console.log('The data is '+data)
})
}
</script>
</body>
</html>
When I click the test me button for the first time
socket.emit('result', { hello: 'world' });
it is emitted one time. And in the console I am getting this printed:
console.log('The data is '+data)
But when I click once again I get this printed thrice:
console.log('The data is '+data)
console.log('The data is '+data)
console.log('The data is '+data)
When I click for the third time I get printed six times:
console.log('The data is '+data)
console.log('The data is '+data)
console.log('The data is '+data)
console.log('The data is '+data)
console.log('The data is '+data)
console.log('The data is '+data)
Like this it is multiplying and going.
Can anyone please give me the insight on how to solve this problem.
Your help is greatly appreciated. Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…