2
    var net = require('net');
    var client = new net.Socket();
    client.connect(port, 'ip', function() {
        console.log('Connected');
        client.write('meesage');
    });
   
    client.on('data', function(data) {
        client.write('meesage');
        console.log('Received: ' + data);
        client.destroy();
    });
   
    client.on('close', function() {
        console.log('Connection closed');
    });

i try used by browserify but not access in browser i want to send message tcp client to a device with net module

2
  • Have you tried Websocket Commented Nov 16, 2022 at 9:02
  • You cannot. If the server you're trying to talk to does not speak HTTP or websocket then the ONLY solution is to write a non-browser program in any language you like (node.js or PHP or Ruby or Java or C# etc.) then have that program expose an HTTP API so that your browser script can talk to that program, then using that program (basically your own server program) connect to the external server via TCP/IP and forward the responses back to the browser via HTTP. Commented Nov 16, 2022 at 11:35

1 Answer 1

1

You cannot run this type of nodejs code in the browser. This relies on the net library which does not run in the browser, it only runs in the nodejs environment. Browserify helps port things between environments to run in the browser, but does not provide native network functionality or file system access (or other similar types of functions) that do not exist in the browser. So, you can only run code in a web page that uses functionality that is supported in the browser.

The browser allows Javascript in web pages to make http requests or connect to webSocket servers or use webRTC and that's about it for networking. You cannot make your own low-level TCP or UDP sockets from browser Javascript.

Sign up to request clarification or add additional context in comments.

3 Comments

so how can i send data to client tcp
@ImanKhaksari - From a browser, use http or webSocket either directly to your target device or to your server and have your server send the data to the desired device using whatever type of connection is required (since the server has no networking limitations).
@ImanKhaksari you can't. Simple as that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.