V
V
Vladimir2019-05-24 22:07:22
JavaScript
Vladimir, 2019-05-24 22:07:22

How to send data to whoever it came from Socket.io?

I found in the documentation that if you write not io, but socket on the server side, it will work, but no, or I'm dumb, I'm doing calculations on the server side, so the script below calculates the player's xp, but it distributes it to everyone, but I need to have Each player had their own HP.
I thought to do it through socket.id, but unfortunately it did not work. Help

//Хп игрока   	
   	socket.on('user fight', function(data) {
   		user_hp = data;
   		if(user_hp<=0) {
   			user_hp = max_user_hp;
   			socket.emit('lose');
   		}
        x2 = user_hp/max_user_hp*100;
        socket.emit('user hp', user_hp);
        if(user_hp>0) socket.emit('user hp line width', x2);
   		if(user_hp<=0) socket.emit('user hp line width', 0);
   		if(hp+user_hp <= 0) {
   			socket.emit('draw');
   		}
   	});
   	
   	//io.sockets.connected[socket.id].emit('class', 'alert');
   	
   	socket.on('hp line for all', function(data) {
        x2 = user_hp/max_user_hp*100;
   		socket.emit('user hp line width', x2);
   		if(user_hp<=0) {
   			socket.emit('user hp line width', 0);
   			socket.emit('lose');
   		}
   		if(hp+user_hp <= 0) {
   			socket.emit('draw');
   		}
   	});
   		
   	//end

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
olezhenka, 2019-05-24
@olezhenka

With socket.emit, as you are doing.

io.on('connect', function(socket) {
  socket.emit('name', ...); // socket = переменная с текущим коннектом отдающаяся в каллбеке события connect.
})

Perhaps you are catching events incorrectly on the client side.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question