2

我需要在 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 服务器中执行上述操作?

4

2 回答 2

5

查看模块的文档net

net.connect(arguments...)

构造一个新的套接字对象并打开一个到给定位置的套接字。

该函数返回一个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);
});

毫无价值,除非有理由不这样做,否则您可以使用模块request方法http来发出 HTTP 请求。

于 2012-06-06T05:59:27.990 回答
0

在 NodeJS 中,我们有一些用于套接字编程的模块,但最流行的是net.

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6969;

// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {

    // We have a connection - a socket object is assigned to the connection automatically
    console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);

    // Add a 'data' event handler to this instance of socket
    sock.on('data', function(data) {

        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        // Write the data back to the socket, the client will receive it as data from the server
        sock.write('You said "' + data + '"');

    });

    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
    });

}).listen(PORT, HOST);

console.log('Server listening on ' + HOST +':'+ PORT);

参考:http ://www.hacksparrow.com/tcp-socket-programming-in-node-js.html

于 2012-06-06T06:05:49.880 回答