Reputation: 2415
I am using Socket.io in a NodeJS + Typescript project, where the client sends a message to ther server and the same message and send back to the client using socket. However, every time I send a new message to the server, the number of times the server sends the message back increments by 1 - which is not how I've programmed it to work. For example, the first time I send a message "x" - the server returns the message "x". The next time I send a message, the server returns that message twice. The next time it happens three times, until the page is refreshed, when it goes back to one. I don't know whats going wrong. Here's the code:
Client:
$("#send").click(function(){
alert("Sending : " + $("#text").val());
socket.emit("toServer", {
message: $("#text").val()
});
socket.on('toClient', function (data) {
alert (data.message);
});
});
Server (app.ts):
function startSocket() {
var io = require('socket.io').listen(server, {log : false});
io.sockets.on('connection', function (socket) {
socket.on('toServer', function (data) {
console.log(data);
socket.emit('toClient', data);
});
});
}
startSocket();
Upvotes: 2
Views: 6829
Reputation: 276209
By registering the event handler inside the click event you would create a new registration each time the click occurred. This would lead to all of these event handlers (depending on the number of times you clicked) to fire when the server sends the message.
In short : the server is sending it only once, you were receiving it multiple times.
Upvotes: 5
Reputation: 2415
Putting the socket receive function outside of the button click event works.
$("#send").click(function(){
alert("Sending : " + $("#text").val());
socket.emit("toServer", {
message: $("#text").val()
});
});
socket.on('toClient', function (data) {
alert (data.message);
});
Upvotes: 1