I've been coding ExpressJS websites which use socket.io for realtime communication, and I use the same port always
const request = require('request')
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
server.listen(3000, () => {
console.log(`Server started: http://localhost:3000`)
})
Is it safe / a healthy practice to use the same port for both the websocket and the express server. Will it cause any problems?
On Scalingo, your application must listen to the port defined in the PORT environment variable dynamically defined by the platform.
Node. js with express is accessible only via port 80. DigitalOcean.
Is it safe / a healthy practice to use the same port for both the websocket and the express server.
It is safe. It is a normal and expected situation to use the same port for your Express server and for your socket.io connections. All socket.io connections start with an http request anyway so socket.io just hooks your existing web server and looks for a particular type of incoming request to open a socket.io connection and it handles that specific request. All other requests are handled normally by your Express server.
The webSocket protocol (which socket.io uses) is specifically designed for this and it was done to allow this because there are some environments (like security-tight corporate environments) where ports other than port 80 can't be used for web traffic. This way, webSockets can be run over port 80 without having to create a whole new host and DNS name for them. They can just use the same server as your web server.
Will it cause any problems?
No.
In high scale environments, there may be scale reasons to use separate hosts or separate server processes for different parts of your server work-load, thus is may be desirable to separate socket.io connections from regular web requests onto different hosts. This can still be done with the same port 80 by using a proxy like nginx that can direct different types of requests to different hosts or different server processes. But, for situations where this type of scaling is not needed, there are no downsides to using the same web server for both Express and for socket.io connections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With