I'm trying to broadcast a simple price updated for a products to all connected clients. It works. Meaning that the broadcast is successful and I can update my values, but what is broadcasted is the problem.
Socket.io broadcast ALL the message since the start of the server, instead of just sending the last one. I can't seem to find how to limit the broadcast to the latest updated price.
Server:
// Broadcast new price
io.sockets.on('connection', function (socket) {
socket.on('bidAction', function(from, msg){
socket.broadcast.emit('bid', { price: new_price, product_id: productID });
});
});
Client:
var socket = io.connect('http://localhost');
socket.on('bid', function (data) {
console.log(data);
// We get the element with price
$('span.price').html(data.price.toFixed(2)) ;
});
// Now when the price is changed
$('.bid').click(function(){
// We emit the bidding
socket.emit('bidAction', {data: 'stuff'});
});
I am not sure if you did this on purpose or by mistake.Right now you have a
function(from, msg)
and trying to broadcast
price: new_price, product_id: productID
new_price and productID are both undefined in your example.
Could you please change your code to the following so that it makes more sense?
Client Side:
socket.emit('bidAction', {new_price: 'stuff' , productID : 'stuff'});
Server Side:
io.sockets.on('connection', function (socket) {
socket.on('bidAction', function(data){
socket.broadcast.emit('bid', { price: data.new_price, product_id: data.productID });
});
});