Expressjs app, using websockets for chat. Use different port for websocket server? - node.js

I'm making an app using node.js' express framework which serves both html content over http and uses websockets for a chat feature. I'm wondering how I can accomplish both at the same time. My idea is to use a different port for websocket connections (so http requests would come to port 3000 and websockets would connect on port 3001) but I don't know if that's a good solution. I'm especially worried about deployment to something like heroku and if I can specify different ports for my app.

I'm wondering how I can accomplish both at the same time.
The webSocket protocol is specially designed so it can run on the same port as your regular web server requests. So, you don't need a separate port in order to have both a web server and chat running using webSockets.
This works because a webSocket connection is always initiated with an http request that sets a few special headers. The receiving web server can then detect those special headers and know that this incoming http request is actually a request to initiate a webSocket connection. With a particular response, the client and server then agree to "upgrade" the connection and switch to the webSocket protocol. From that point on, that particular TCP connection uses the webSocket protocol.
Meanwhile any incoming http request that does not have the special webSocket headers on it is treated by your web server as just a regular http request. In this way, the same server and the same port can be used for both webSocket connections and regular http requests. No second port is needed.
Another advantage of this scheme is that the client can avoid the cross-origin issues that it would run into if it was trying to use a different port than the web page it was loaded from.
I'm especially worried about deployment to something like heroku and
if I can specify different ports for my app.
If you were to actually use two ports, then you would need to create two separate servers, one listening on each port since a given server can only listen on one port. In node.js, the two servers could both be in the same node.js app (making it easier to share data between them) or you could put them in completely separate node.js processes (your choice).
And, if you used multiple ports, you'd also have to support CORS so that the browser would be allowed to connect to the separate port (to avoid same-origin restrictions).

Related

Difference in server port and websocket port in node.js chat application

I am trying to create a multi room chat application in node.js using socket.io and express. I am confused between use of server port and websocket port. I understand server port is used by the client to connect to server. But not sure about use of websocket port.
Thanks & Regards..
webSockets can share the same port as your web server and this is a common configuration. The reason this works is because of how a webSocket establishes a connection (all webSocket connections are initiated with an HTTP request). It works like this:
Client makes an HTTP request to a web server with a header specifying that they want to "upgrade" to the webSocket protocol and sends a security-related header.
Web server sees the upgrade request and, if it has support enabled for webSocket connections, it will respond with a 101 request (switching protocols) and another security related header.
Client gets the accepted upgrade and both ends switch to the webSocket protocol and the original TCP socket that started out using the HTTP protocol is now using the webSocket protocol.
In this manner, the same port and webServer can be used for regular HTTP requests or webSocket connection requests.
For a chat application it is common to use a webSocket connection because it is a continuous connection that more easily allows the server to send information directly to the client which is often needed in a chat application.
To understand more about how a webSocket connection and server work, see this reference on MDN: Writing WebSocket servers which shows the step by step process for initiating a webSocket connection.
Server socket is used by server... that keeps listening to coming sockets request in a loop... and websocket sends a request to server socket and bound a connection between two devices...
If you have / want to have web clients, WebSocket is going to be required, because there is no access to 'regular' TCP (or UDP) sockets from browser-based JavaScript (and I assume you do not want Flash, SilverLight or Java Applets, in 2017). WebSocket is not special because of the port number, but it is special because of the protocol: a WebSocket connection starts as a regular HTTP connection, and protocol upgrade reconfigures it afterwards, it is designed for the browser-world, and even capable of traversing HTTP proxies. After establishing the connection, it provides a full-duplex, bi-directional message stream, very usable for chat applications.
And because of being a Web-thing, you could simply use port 80, if you are allowed to.

http server on top of net server

I implemented 2 webservers with express. One is the main, one is a microservice.
They are communicating through a HTTP REST API, and we had historically a socket.io server started on the microservice to watch the up/down status from the main server.
----HTTP-----
[main server] [microservice]
--socket.io--
I then realized that socket.io is not the right tool for that. So I decided to trade socket.io for a raw TCP socket.
So the question is : Is that possible to start the http server "ON TOP" of a raw TCP server (on the same port) ? (allowing to connect via TCP client AND to send HTTP requests ?)
I have this so far :
const app = express();
const server = http.createServer(app);
// const io = sio(server);
server.listen(config.port, config.ip, callback);
and I'm trying to integrate with this
What I'm trying to achieve, and achieved successuly with socket.io, is starting a socket server on the microservice, connect to it on the main server, keep it alive, and watch for events to keep a global variable boolean "connected" in sync with it. I'm using this variable to aknowledge the my frontend of microservice state, also to pre-check if I should try to request the microservice when requested, and also for loggin purposes. I'd like to avoid manual polling, firstly for maintenability, and also for realtime purpose.
Is that possible to start the http server "ON TOP" of a raw TCP server (on the same port) ?
Sort of, not really. HTTP runs on top of TCP. So, you could technically open a raw TCP server and then write your own code to parse incoming HTTP requests and send out legal HTTP responses. But, now you've just written your own HTTP server so it's no longer raw TCP.
The challenge with trying to have a single server that accepts both HTTP and some other protocol is that your server has to be able to figure out for any given incoming packets, what it is supposed to do with it. Is it an HTTP request? Or is it your other type of custom request. It would be technically feasible to write such a thing.
Or, you could use the webSocket technique that starts out as an HTTP request, but requests an upgrade to some other protocol using the upgrade header. It is fully defined in the http spec how to do this.
But, unless you have some network restriction that you can only have one server or one open port, I'd ask why? It's a complicated way to do things. It doesn't really cost anything to just use a different port and a different listening server for the different type of communication. And, when each server is listening only for one type of traffic, things are a heck of a lot simpler. You can use a standard HTTP server for your HTTP requests and you can use your own custom TCP server for your custom TCP requests.
I can't really tell from your question what the real problem is here that you're trying to solve. If you just want to test if your HTTP server is up/down, then use some external process that just queries one of your HTTP REST API calls every once in a while and then discerns whether the server is responding as expected. There are many existing bodies of code that can be configured to do this too (it's a common task to check on the well being of a web server).
The code you link to shows a sample server that just sends back any message that it receives (called an echo server). This is just a classic test server for a client to connect to as a test. The second code block is a sample piece of client code to connect to a server, send a short message and then disconnect.
From your comments:
The underlying TCP server wouldn't even be used for messaging, it just would be used to watch connect/disconnect events
The http server already inherits from a TCP server so it has all the same events for the server itself. You can see all those events in the http server doc. I don't know exactly what you want, but there are server lifetime events such as:
listening (server now listening)
close (server now closed)
And, there are server activity events such as:
connect (new client connected)
request (new client issues a request)
And, from the request event, you can get both the httpClientRequest and httpServerResponse objects which allow you to monitor the lifetime of an individual connection, including event get the actual socket object of an incoming connection.
Here's a code example for the connect event right in the http server doc.

Ports and security in URL

I'm going to use socket.io on nodeJs in order to be able to send messages from my server to my client.
Node runs on a separate port from what I normally use for my hosting. Is there any safety risk in using the port number in the url in production? For example, I'm directing users to domain.tld:0000?
There are no more security risks in exposing node.js on another port than running node.js itself exposed to the internet.

SocketIO on port 80 together with Express

I have ExspressJS app run with Socket.io, due to firewall issues with higher port for SIO i want to switch that both will work on port 80.
Found this small article and on my dev machine it's look working good.
My question is, is it really goo to do that? is it a good practice? if not why?
Please advise.
It makes absolute sense to run socket.io and your web server on the same port.
The webSocket protocol (which socket.io is based on) is specifically designed for this to be the primary way that socket.io is used for a bunch of reasons including same-origin permissions and client and server firewall routing of port 80.
In case you didn't realize it, every socket.io connection starts with an HTTP request to a specific route and then once the initial handshake between client and server has been confirmed, then the protocol is "upgraded" from HTTP to webSocket. Because all socket.io connections connect in on a very specific route, all other HTTP connections can easily be separated out and be treated by your web server as regular web requests.

Websockets with nodejs and Symfony 2

I'm running a real time web application which uses Symfony 2 PHP framework on the backend. I want to implement websockets for my real time interaction. Is it possible to install a node.js server on the same machine as my Symfony 2 server to handle websocket connections? If so, is it standard to open another port (say 81) to handle the websocket connection?
Yes, it is possible. Why not? It's just another application.
As for the second question. You can either open another port, which is easy to handle (WebSockets are not limited with cross-origin policy) but you may lose some data (cookies) or you can put a proxy which will send HTTP requests to web server and WS requests to Node.JS server. The latter can be recognized by having special header Upgrade: websocket. Either way WebSocket server has to listen on different port (unless you are developing application entirely in Node.JS).

Resources