如何在浏览器中使用Node.js中的net模块? [英] How to use the net module from Node.js with browserify?

查看:346
本文介绍了如何在浏览器中使用Node.js中的net模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在客户端(在浏览器中)使用Node.js的 net 模块:

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

var net = require('net');

所以我查找了如何将Node.js模块获取到客户端,而browserify似乎是回答。我使用jQuery进行了尝试,它的魅力十足。
但是由于某些原因, net 模块不起作用。如果我写 require('jquery')很好,但是如果我写 require('net')不起作用,这意味着我捆绑的.js文件为空。

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.

我尝试搜索其他内容,但发现的唯一内容是 net-browserify 。这样,至少我的bundle.js文件已满,但使用此文件我遇到了JavaScript错误(它与 connect 函数有关)。

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');
});

我认为net-browserify允许您使用特定的 connect 函数,但我不知道是哪个。

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

如何在客户端使用Node.js的net模块?

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

推荐答案

这是因为 net 允许您访问原始TCP套接字-浏览器根本无法做到从JavaScript端开始。在编写这样的API之前, net 不可能被移植到客户端(允许任意的TCP通信)。

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).

如果您想从客户端向服务器发送TCP数据,最好的选择是使用 socket.io模块或ws一个。

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.

如果您希望客户直接进行交流,最好的办法就是研究WebRTC

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

这篇关于如何在浏览器中使用Node.js中的net模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆