I am using Socket.io in my project. I create a plugin for my sockets...
await server.register(socket_connections);
Where socket_connections
is the following...
const connect = require("./controllers/connect");
module.exports = {
name: "SocketPlugin",
register: connect.socket
};
And where connect.socket
is my socket connection...
exports.socket = async (server) => {
const io = require("socket.io")(server.listener);
io.on("connection", socket => {
console.log("Socket Connection");
});
}
My problem is that io
is defined inside the plugin, which shouldn't be the case. If it is defined inside the plugin, the sever connection will keep restarting. For example, in my server console, the following is printed at regular intervals...
Socket Connection
Socket Connection
Socket Connection
...
The solution, I realized, is to define the server connection outside of the plugin. So I want to define const io = require("socket.io")(server.listener);
outside of the plugin, preferably in the same file where server.register
is taking place, and pass the connection down to the plugin.
Can this be done in Hapi.js
? This is the only way I can make a proper socket connection it seems, otherwise I have to do away entirely with the plugin which is a little painstaking.
I found a workaround to prevent my sockets from periodically disconnecting. The answer is here.
Essentially my server pings the client every 25 seconds and the client must periodically pong the server every 25 seconds. 25 seconds is just an arbitrary number, you can probably get away with more.
By pinging and ponging, this prevents socket.io from ever restarting, which it seems to do when it is idle for too long.