How do I use a network module from Node.js with a browser?
I want to use a module net
with Node.js on the client side (in the browser):
var net = require('net');
So, I looked at how to get the client Node.js modules and it looks like the response to this request looks like a browser. I tried it with jQuery and it worked like a charm. But for some reason the module net
doesn't want to work. If I write require('jquery')
it works fine, but if I write require('net')
it doesn't work, i.e. my associated .js file is empty.
I tried looking for something else, but the only one I found is net-browserify on Github . Doing this at least populates my bundle.js file, but I get a JavaScript error using this (it has something to do with the function connect
).
This is my code that works great on the server side:
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 response
});
client.on('close', function() {
console.log('Connection closed');
});
I'm guessing net-browserify allows a specific feature connect
, but I don't know which one.
How can I use the network module with Node.js client side?
source to share
This is because it net
gives you access to raw TCP sockets that browsers simply cannot do from the JavaScript end. It is not possible to net
be ported to the client side until such an API is written (allowing arbitrary tcp traffic).
Best of all if you want to send tcp data from client to server use websockets using socket.io module or the former.
Your best bet if you want clients to communicate directly is to look in WebRTC
source to share