Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the net module from Node.js with browserify?

I want to use the net module from Node.js on the client side (in the browser):

var net = require('net');

So I looked up how to get Node.js modules to the client, and browserify seems to be the answer. I tried it with jQuery and it worked like a charm. But for some reason the net module does not want to work. If I write require('jquery') it works fine, but if I write require('net') it does not work, meaning my bundled .js file is empty.

I tried to search for something else, but the only thing I found is net-browserify on Github. With this, at least my bundle.js file is filled, but I get a JavaScript error using this (it has something to do with the connect function).

This is my code which works on the server side just fine:

var net = require('net-browserify');
//or var net = require('net');

var client = new net.Socket();
client.connect({port:25003}, function() {
    console.log('Connected');
    client.write('Hello, server! Love, Client.');
});

client.on('data', function(data) {
    console.log('Received: ' + data);
    client.destroy(); // kill client after server's response
});

client.on('close', function() {
    console.log('Connection closed');
});

I assume that net-browserify lets you use a specific connect function, but I don't know which.

How can I use the net module from Node.js on the client side?

like image 414
Captain GouLash Avatar asked Jun 14 '15 15:06

Captain GouLash


1 Answers

This is because net gives you access to raw TCP sockets - which browsers simply cannot do from the JavaScript end. It is impossible for net to ever be ported to the client side until such an API is written (allowing arbitrary tcp traffic).

Your best bet if you want to send tcp data from the client to the server is using web sockets using the socket.io module or the ws one.

Your best bet if you want clients to communicate directly is to look into WebRTC

like image 76
Benjamin Gruenbaum Avatar answered Oct 04 '22 21:10

Benjamin Gruenbaum