Should I Create A Route Specific For Socketio?
Solution 1:
Should I create a route for SocketIO or what?
No. When you do this:
const io = socketIO(server)
The socket.io library already installed its own route handler for routes starting with /socket.io
and any other routes it needs. You don't need to do that yourself.
You do, however, have a problem because you're hooking up socket.io to server that you never started.
When you do this:
app.listen(PORT, () =>console.log(`Application up and running on ${PORT}`))
That creates a new http server and then calls .listen()
on it and returns that new server. You will need to capture that server and hook up socket.io to it:
So, replace this:
const server = http.createServer(app)
const io = socketIO(server)
app.listen(PORT, () =>console.log(`Application up and running on ${PORT}`))
With this:
const server = app.listen(PORT, () =>console.log(`Application up and running on ${PORT}`))
const io = socketIO(server);
Then, you're creating and starting just one http server and hooking up both Express and socket.io to it. They can both share the same http server on the same port. Socket.io will use the route prefix /socket.io
to distinguish its own routes and once a given socket.io connection has been established, that specific connection switches protocol to the webSocket protocol (with socket.io data frame on top of it) and is no longer using http any more.
Solution 2:
Instead of:
app.listen(PORT, () => console.log(`Application up and running on ${PORT}`))
Use this:
server.listen(PORT, () => console.log(`Application up and running on ${PORT}`))
Reason: The server instance you are assigning to socketIO
is not the same as the instance of server you are listening to.
With express you can pass the server instance like this:
var express = require('express');
var app = express();
...
...
...
var server = app.listen(PORT);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
...
});
You can refer this: Express.js - app.listen vs server.listen
Post a Comment for "Should I Create A Route Specific For Socketio?"