我需要在 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/