How to create a nodejs HTTP server with an existing TLS client socket? - node.js

I have a nodejs TLS client socket on my laptop, connected to a TLS server socket on a different computer (server). The server cannot connect to my laptop. The laptop needs to initiate the connection.
Now I want the server to make requests to my laptop. The idea is to reuse the HTTP protocol. Is there a way to create a HTTP server using the existing TLS client socket?
This way, the server machine can make a HTTP request, and the client TLS receives it, and the HTTP server would parse it? Or am I missing something?

Once you have a TCP socket open between laptop and server, you can send data either way over that socket. So, if the server wants to send some query to the laptop, it can do so just fine. You will have to invent your own protocol on top of TCP to do that, but it could be as simple as a text/line based protocol if you want.
Or, instead of making a plain TCP connection, you can make a webSocket or socket.io connection from the laptop to the server (instead of the plain TCP connection) and then either side can send messages either way and the protocol part is already taken care of. If you use socket.io, it will automatically reconnect if the connection is interrupted too.
There is no simple way to attach an HTTP server to an existing TCP socket and it would be fraught with difficulties too because an HTTP connection is generally not a continuous connection over which you send many separate requests (advanced versions of http can do that, but I doubt you want to get into implementing all that logic on both ends). You could use the HTTP protocol over your existing TCP socket, but that would probably be substantially more work to implement than just use the webSocket/socket.io idea above.

Related

Call Normal Socket from a Web Browser

I have a webapp written in ReactJS.
And what I'm trying to do is communicate with a normal TCP Socket which is running on localhost. (The device which is listening for the requests is an Eftpos terminal). So I would like to send purchase commands and receive responses from it.
How can I communicate with the normal TCP socket from my webapp? From what I understand is that I cannot just communicate with the TCP socket from the webapp. Since webapps only support WebSockets which are different. Whats another way?
Javascript in a browser can do http, webSocket and webRTC. Browser Javascript (without custom add-ons that contain their own native code) cannot do a plain TCP connection.
If you want to connect to something that requires a plain TCP connection, then you need to connect to your server using either http or webSocket and have your server connect to the regular TCP socket and your server can translate between them. This is often referred to as a proxy.
So, for purposes of this explanation, let's imagine you want to connect to some service that uses a plain TCP socket and you need to send lines of text to it and get lines of text in response. Your client has to pick between http or webSocket for the browser-to-your-server transport so let's imagine you're using webSocket. The sequence of events could look like this:
Browser client connects to your server with a webSocket.
Your server receives incoming webSocket connection and since it knows it will be acting as a proxy to a server that uses a plain TCP socket, it opens that socket on behalf of that user.
Browser client sends first request over webSocket.
Your server receives that first request and translates it into whatever format is needed for the TCP socket and sends that over the TCP socket.
When your server gets a response from the TCP socket, it translates that response into a webSocket packet and sends that back to the client.
The client receives the response on its webSocket connection.
Repeat as long as you want.
When client closes webSocket connection, server will close TCP connection to other server.
The only way is to proxy the data server-side.
You can make that TCP connection server-side, and relay the data over a Websocket connection to the browser client.

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.

Node.js reuse tcp connection

I'm new in node.js
So the question can be quite naive.
I want to use node.js as a proxy between the javascript client and a windows program which has a API working through a defined port.
So browser sends HTTP request to node.js.
Node.js opens connection with the windows program, sends request, get a respons and returns the response to the javascript that called node.js ( AJAX )
Actually it has been realized so and works.
The problem is that windows program wants to work persistent.
So once the connection is opened it should stay alive.
And my node.js script opens connection. And the next call to node.js try to open connection again. And that leads to error.
So the question - what is the right way and middles to reuse the TCP connection in node.js.
So that next call won't open new connection but go on with already opened one.
It is possible, but requires some coding on your side.
If it is not sticky (the same HTTP client does not require to use the same TCP connection):
Open an connection pools of TCP connections to the windows program
Listen to HTTP requests
If a HTTP request arrives find an unused TCP connection (if none is available, make a new one or wait)
Query the windows program, return the results to who ever called the HTTP request
Mark the TCP connection as free
If it is sticky (always use the same TCP connection for the same HTTP client):
If a HTTP clients connect and he hasn't one, give him session.
If not available for the session: create a TCP connection
Make the request, return the result
Store the TCP "connection" somewhere where you could reach it when the next request comes in and you could identify it by the HTTP clients session (Maybe make a timeout for clearing up)

Single persistent TCP connection for server to server connection

I have to implement a server to server communication protocol using a SINGLE PERSISTENT TCP connection. The server at both the ends of this connection are implemented using "multi-threaded and asynchronous event-driven model". Both these servers are implemented in C++ and Pthreads on Linux. Server A always sends requests to Server B and Server B responds with a response. Server B doesn't send any requests to Server A, it just responds to the requests it receives. Could some one post me a sample code for this communication? Could you help me with the code for both Server A and Server B? Or please point me to any old answers or any websites where i can find a prototype code. Thanks in advance.
TCP servers cannot open connections to TCP servers. There is no IP protocol for that. One of the two servers must run a TCP client as a subsystem. The exact mechanics of how you do that depend on your client<>server protocol - the 'server-client' could log in to the 'client-server' with a unique username/password, or could use a different server listening port.
It's up to you:)

Resources