I need to write socket in nodejs such as in PHP. In PHP language I do something like the following:
$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);
How can I do thing above in nodejs server?
Take a look at the documentation for the
netmodule.The function returns a
Socket.There’s a small example snippet on the page to demonstrate its use:
It’s been a while since I wrote PHP, but I would try this as a translation of your code:
It’s worth nothing that, unless there’s a reason not to, you can use the
requestmethod of thehttpmodule to make HTTP requests.