Reputation: 601
I want to run Hapi.js together with socket.io. That would be great if I had separate connections for socket.io and hapi app using the same server because I want to use Hapi auth cookies in my socket
I tried few solutions, but none of them is working and my server is crashing. I tried to run socket.io on the same port as hapi and my app started, but I got "This localhost page can not be found" error. What did I do wrong? Any help will be appreciated
Here's my code:
const Hapi = require('hapi');
const server = new Hapi.Server();
const Config = require('./config/config.js');
const port = Number(process.env.PORT || 3000);
const io = require("socket.io")(port);
server.connection({
port: port
});
// my routes are here...
io.on("connection", function (socket) {
console.log('connected');
// Do all the socket stuff here.
})
server.start(function(err) {
if (err) {
console.error(err);
throw err;
}
console.log('Server started at %s', server.info.uri);
});
Upvotes: 3
Views: 6237
Reputation: 601
I simply solved my problem, by creating two separate connections. Now everything is working great!
Here's how my code looks now:
const Hapi = require('hapi');
const server = new Hapi.Server();
const Config = require('./config/config.js');
const port = Number(process.env.PORT || 3000);
server.connection({ port: port, labels: ['app'] });
server.connection({ port: 8000, labels: ['chat'] });
const app = server.select('app');
app.register([
// all app's stuff goes here
]);
var io = require('socket.io')(server.select('chat').listener);
io.on("connection", function (socket) {
console.log('connected');
// Do all the socket stuff here.
})
server.start(function(err) {
if (err) {
console.error(err);
throw err;
}
console.log('Server started');
});
That website helped me a lot
Upvotes: 9
Reputation: 446
Some times you might just want to use one port on your environment. You could actually share same hapi connection between socket.io and http server.
Hapi doesn't want you use the same port for multiple connects. See here about this. If you did that, you might not got any error from Hapi at initialization time but your second connection will always get 404 error.
Small changes from @Mattonit's code for one port scenario.
const Hapi = require('hapi');
const server = new Hapi.Server();
const Config = require('./config/config.js');
const port = Number(process.env.PORT || 3000);
server.connection({ port: port, labels: ['app'] });
const app = server.select('app');
app.register([
// all app's stuff goes here
]);
var io = require('socket.io')(app.listener);
io.on("connection", function (socket) {
console.log('connected');
// Do all the socket stuff here.
})
server.start(function(err) {
if (err) {
console.error(err);
throw err;
}
console.log('Server started');
});
Upvotes: 4