【发布时间】:2015-03-19 12:26:05
【问题描述】:
大家
我对 node.js 很陌生。 我正在尝试使用 node.js 做一个 tcp 服务器 客户端。到目前为止,一切都很好。 服务器脚本可以运行了。 客户端脚本也可以正常运行。
但问题是我只能通过键入命令 (node client.js) 让客户端从终端运行。
问题是我想在浏览器中运行它,这样我就可以把从服务器接收到的数据显示在浏览器上。
我该怎么做?
请帮忙。
卡温。
这是客户端代码。 (我不记得最初是谁创建了这个脚本。我从某个地方复制并粘贴了它,但忘记了我从中获取链接的书签。很抱歉没有将功劳归功于此脚本的所有者。)
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 和浏览器是两个不同的环境。如果您使用环境特有的功能(例如 TCP 套接字),则不能在其他环境中使用相同的脚本。
-
谢谢。所以我想我可能不得不改变我的计划来实现这一目标。
标签: javascript node.js