buydadip
buydadip

Reputation: 9417

Socket.io keeps trying to establish a connection

The client side is connecting to my server using the following...

var socket = io.connect('http://localhost:52805');

and on the server I am making this connection using...

// Establish a connection with a WebSocket.
io.on("connection", socket => {

  console.log("Socket Connection");

  ...

Now if I check the console on the server side, in the console I get the following in regular intervals...

Socket Connection
Socket Connection
Socket Connection
Socket Connection
...

It keeps printing out Socket Connection even though I am not refreshing the client.

What is causing this and is this normal? If not, what can I do to prevent this? Is it normal for the client to keep polling the server?

EDIT

As an extra note, I am using Socket.io as a plugin with Hapi.js...

const sockets = require("./src/Playlist/index");


// Define the server.
const server = new Hapi.Server({ 
  port: process.env.PORT, 
  routes: { 
    cors: true 
  } 
});

// Socket.io plugin.
await server.register(sockets);

// Start the server.
await server.start();

Where sockets is just a reference to the io.on("connection") mentioned above.

Upvotes: 3

Views: 766

Answers (1)

aravindanve
aravindanve

Reputation: 1069

Have you tried initializing io with server.listener like this:

const Hapi = require('hapi');
const server = new Hapi.Server();
const io = require('socket.io')(server.listener); // <--- THIS

...


io.on('connection', function (socket) {
    ...
});

...

server.start();

See: http://matt-harrison.com/using-hapi-js-with-socket-io/

Upvotes: 1

Related Questions