sockets - nodejs中的套接字

标签 sockets node.js

我需要在 nodejs 中编写套接字,例如在 PHP 中。在 PHP 语言中,我执行如下操作:

$http_request  = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "User-Agent: Picatcha/PHP\r\n";
$http_request .= "Content-Length: " . strlen($data) . "\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "\r\n";
$http_request .= $data;

$response = '';
$fs = @fsockopen($host, $port, $errno, $errstr, 10)
if (FALSE == $fs) {
  die('Could not open socket');
}

fwrite($fs, $http_request);

我怎样才能在 nodejs 服务器上做上面的事情?

最佳答案

看看the documentation for the net module .

net.connect(arguments...)

Construct a new socket object and opens a socket to the given location.

函数返回a Socket .

页面上有一个小示例片段来演示其用法:

var net = require('net');
var client = net.connect(8124, function() { //'connect' listener
  console.log('client connected');
  client.write('world!\r\n');
});
client.on('data', function(data) {
  console.log(data.toString());
  client.end();
});
client.on('end', function() {
  console.log('client disconnected');
});

自从我编写 PHP 以来已经有一段时间了,但我会尝试将其作为您代码的翻译:

var net = require('net');

var http_request;
http_request  = "POST " + path + " HTTP/1.0\r\n";
http_request += "Host: " + host + "\r\n";
http_request += "User-Agent: Picatcha/PHP\r\n";
http_request += "Content-Length: " + data.length + "\r\n";
http_request += "Content-Type: application/x-www-form-urlencoded;\r\n";
http_request += "\r\n";
http_request += data;

var client = net.connect(80, host, function() {
  client.end(http_request);
});

毫无意义的是,除非有理由不这样做,否则您可以使用 the request method of the http module发出 HTTP 请求。

关于sockets - nodejs中的套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10908765/

相关文章:

c++ - boost .Asio : Is it a good thing to use a `io_service` per connection/socket?

c++ - 接收 recv 数据直到流结束(使用 HTTP)?

Java:安全套接字接受

javascript - Node js array.push 'not' 工作

node.js - 异步 lambda 函数内的函数被忽略

javascript - 如何在nodemailer中正确发送电子邮件并关闭smtp连接?

c++ - boost 从 tcp 套接字接收数据

sockets - 如何在 Telnet 中创建 HTTP 请求

javascript - 打包flow中编写的npm项目

javascript - node.js 事件循环如何记住它需要在长时间运行的操作完成后回调?