Connecting to Tcp Socket from Browser Using JavaScript

Create TCP/IP socket in client-side javascript

No, you can't make an arbitrary TCP connection from a web page in any browser.

Web Sockets are fundamentally different than TCP sockets... they're essentially unrelated. They're a thin layer on top of HTTP along with a client API which allows bidirectional communication between a Web Socket client and a server supporting Web Sockets.

There are proxy servers you can run that allow connecting through them to make TCP connections, but this of course is a server feature and not something you can do in-browser alone.

How to connect to a TCP server and pass a Javascript to it

Reading [1], We can assume socket-io isn't the perfect fit for you, because that Server you have sound like a typical tcp-socket server, not a socket.io server ( which requires special headers ) or a web-socket server.

So you only needs "net" library to do the job.

const net = require('net');

// module to send a message to TCP-socket server and wait for the response from socket-server
const sendAndReceive = async (client, message) => {

client.write(message);

let response = null
await ( new Promise( (resolve, reject) => {
client.on('data', function(data) {
response = data;
resolve()
});
}))

return response;

}

// send a single message to the socket-server and print the response
const sendJSCode = (message) => {

// create socket-client
const client = new net.Socket();
client.connect(3040, 'localhost', async function() {
console.log('Connected');

// send message and receive response
const response = await sendAndReceive(client, message)

// parse and print repsonse string
const stringifiedResponse = Buffer.from(response).toString()
console.log('from server: ', stringifiedResponse)

// clean up connection
client.destroy()

});


}

sendJSCode('var Out; \n Out="TheSky Build=" + Application.build \n\r')
  • This script will:

    • Initiate a socket client
    • on connection successfully, client sends a message
    • client receives back response from that message
    • client prints response to terminal
  • Note that TheSkyX has a limitation of 4096 bytes for each message[2], any more than that and we will need to chunk the message. So you may want to keep the js-code short and precise.

  • that snippet I gave is minimal, it doesn't handle errors from server. If you want, you can add client.on("error", .. ) to handle it.

  • Your point of connecting to the socket server directly from browser is very intriguing, unfortunately it is not allowed by modern browsers natively due to security concerns 3

[1] https://socket.io/docs/#What-Socket-IO-is-not:~:text=That%20is%20why%20a%20WebSocket%20client,to%20a%20plain%20WebSocket%20server%20either.

[2] https://www.bisque.com/wp-content/scripttheskyx/scriptOverSocket.html#MSearchField:~:text=set%20to%204096%20bytes

Call Normal Socket from a Web Browser

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.

Is there a way to do a tcp connection to an IP with javascript?

I eventually found a solution.

What I had to do was create a windows application that will act as a websocket server.

When installing the program it will create a URI Scheme to be able to call itself from a link like myapp://start

Here is the code to edit the registry to add a custom URI Scheme:

static void Main(string[] args) {

try {

// SET PATH OF SERVER
String path = Environment.GetCommandLineArgs()[0];

// GET KEY
RegistryKey key = Registry.ClassesRoot.OpenSubKey("myApp");

// CHECK FOR KEY
if (key == null) {


// SET KEY
key = Registry.ClassesRoot.CreateSubKey("myApp");
key.SetValue(string.Empty, "URL: myApp Protocol");
key.SetValue("URL Protocol", string.Empty);

// SET COMMAND
key = key.CreateSubKey(@"shell\open\command");
key.SetValue(string.Empty, path + " " + "%1");
//%1 represents the argument - this tells windows to open this program with an argument / parameter


}

// CLOSE
key.Close();

} catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.ReadKey();

}



}

Then in the browser it will call that url which starts the program.
The websocket will get created and send it to the localhost:port server program that is running.

The windows program will do everything to get the data then send it as raw tcp/ip bytes to the terminal.
Once the terminal sends data back to the windows program, the windows program will then forward that back to the websocket for the browser to handle the information.

The windows program then will kill all connections and quit.

Browser with JavaScript TCP Client

The problem is that you are using just pure TCP connection in NodeJS. If you want to communicate via WebSockets you have to use some WS module on the server side (NodeJS) as well. Have a look at https://github.com/einaros/ws

Is it possible to connect to Node.js's net moudle from browser?

The browser does not contain the capability for Javascript in a regular web page to make a straight TCP socket connection to some server.

Browser Javascript has access to the following network connection features:

  1. Make an http/https request to an external server.
  2. Make a webSocket connection to an external server.
  3. Use webRTC to communicate with other computers

In all these cases, you must use the libraries built into the browser in order to initiate connections on these specific protocols.

There is no capability built into the browser for a plain TCP socket connection. A webSocket (which can only connect to a webSocket server) is probably the closest you can come.



Related Topics



Leave a reply



Submit