简体   繁体   English

如何将 Node.js 中的 net 模块与 browserify 一起使用?

[英]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):我想在客户端(在浏览器中)使用 Node.js 的net模块:

var net = require('net');

So I looked up how to get Node.js modules to the client, and browserify seems to be the answer.所以我查找了如何将 Node.js 模块发送到客户端,而 browserify 似乎是答案。 I tried it with jQuery and it worked like a charm.我用 jQuery 尝试了它,它就像一个魅力。 But for some reason the net module does not want to work.但出于某种原因, net模块不想工作。 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.如果我写require('jquery')它工作正常,但如果我写require('net')它不起作用,这意味着我捆绑的 .js 文件是空的。

I tried to search for something else, but the only thing I found is net-browserify on Github .我试图搜索其他东西,但我唯一找到的是Github 上的 net-browserify 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).有了这个,至少我的 bundle.js 文件被填满了,但是我使用这个得到了一个 JavaScript 错误(它与connect函数有关)。

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.我假设 net-browserify 允许您使用特定的connect功能,但我不知道是哪个。

How can I use the net module from Node.js on the client side?如何在客户端使用 Node.js 的 net 模块?

This is because net gives you access to raw TCP sockets - which browsers simply cannot do from the JavaScript end.这是因为net使您可以访问原始 TCP 套接字——浏览器在 JavaScript 端根本无法做到这一点。 It is impossible for net to ever be ported to the client side until such an API is written (allowing arbitrary tcp traffic).在编写这样的 API(允许任意 tcp 流量)之前,不可能将net移植到客户端。

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.如果您想将 tcp 数据从客户端发送到服务器,最好的选择是使用使用socket.io 模块或 ws 的 web 套接字。

Your best bet if you want clients to communicate directly is to look into WebRTC如果您希望客户直接沟通,最好的选择是研究 WebRTC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM