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

ⅰ亾dé卋堺 提交于 2019-11-28 01:33:48

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/30831243/how-to-use-the-net-module-from-node-js-with-browserify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!