Just_Ice
Just_Ice

Reputation: 563

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?

Upvotes: 0

Views: 1108

Answers (2)

jfriend00
jfriend00

Reputation: 707976

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:

  1. Browser client connects to your server with a webSocket.
  2. 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.
  3. Browser client sends first request over webSocket.
  4. 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.
  5. 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.
  6. The client receives the response on its webSocket connection.
  7. Repeat as long as you want.
  8. When client closes webSocket connection, server will close TCP connection to other server.

Upvotes: 1

Brad
Brad

Reputation: 163528

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.

Upvotes: 1

Related Questions