I
I
Ivan R.2016-09-22 17:37:34
JavaScript
Ivan R., 2016-09-22 17:37:34

Socket.io on Node.js. A simple example, but the exchange is incorrect. Why?

Hi everybody. I take the simplest, minimal example. In fact, from the manual.
Server:

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  console.log('client connect');
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Customer:
var socket = require('socket.io-client')('http://localhost:3000');

socket.on('connect', function() {
    console.log('connected to server');
    socket.on('news', function (data) {
      console.log(data);
      socket.emit('my other event', { my: 'data' });
    });
});

I launch the server part in the first terminal, the client part in the second one. All they do is exchange a message.
The server sends a message: { hello: 'world' }
Client, in response to it: { my: 'data' }
Next, I restart the server. And there are already 2 messages. I restart again, I get an exchange of 3 messages. And so on.... If you restart the client, everything will be restored. What nonsense? That is, when the connection between the client and the server is lost and next restored, the number of messages increases by 1.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
miki131, 2016-09-23
@RtIvan

The connect event on the client fires every time the code it connects to the server.
When you restart the server, the connection is broken, and then connect again .
Every time you connect , you hang up socket.on('news'... - you don't need to do that.

var socket = require('socket.io-client')('http://localhost:3000');

socket.on('connect', function() {
  console.log('connected to server');
});

socket.on('news', function (data) {
  console.log(data);
  socket.emit('my other event', { my: 'data' });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question