如何在浏览器上运行node.js客户端 [英] how to run node.js client on browser

查看:400
本文介绍了如何在浏览器上运行node.js客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人

我对node.js很新。
我正在尝试使用node.js来执行tcp服务器< - >客户端。到现在为止还挺好。
服务器脚本可以运行Ok。
此外客户端脚本可以运行OK。

I'm very new to node.js. I'm trying to do a tcp server <-> client using node.js. So far so good. The server script can be run Ok. Also the client script can be run OK.

但问题是我只能通过输入命令(节点客户端)从终端运行客户端。 js)。

我希望在浏览器中运行它,这样我就可以从浏览器上的服务器显示中获取数据。

But the problem is I could only get the client to run from the terminal by typing command (node client.js).
The thing is I would like to run it in a browser so I could take the data received from server display on browser.

我该怎么做?

请帮忙。

Kawin。

这是客户端代码。 (我不记得是谁最初创建了这个脚本。我从某个地方复制并粘贴它,但忘记了我从中获取链接的书签。很抱歉没有把这个功能归功于这个脚本的所有者。)

This is the client code. (I can't remember who originally created this script. I copy and paste it from somewhere but forget to bookmark from which I get the link. Sorry for not putting the credit to the owner of this script.)

var net = require('net');

var HOST = '192.168.0.88';
var PORT = 8888;

var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the   server will receive it as message from the client 
    client.write('B2\r\n');
});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();
});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
}); 

谢谢。

推荐答案

Node.js不是浏览器javascript。它有很多部分使用浏览器上下文中不可用的操作系统功能。在停留在客户端的浏览器中做你想要做的事情的方法是不使用TCP套接字,而是查看WebSockets(例如socket.io,它提供服务器和浏览器客户端)。

Node.js is not browser javascript. There are many parts of it that use OS features not available in a browser context. The way to do what you're looking to do while staying in the browser for the client, is to not use a TCP socket, but instead look into WebSockets (e.g. socket.io, which offers server and browser clients).

这篇关于如何在浏览器上运行node.js客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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