2

PHPなどのnodejsでソケットを作成する必要があります。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 に答える