nodejs中的套接字

时间:2012-06-06 05:47:47

标签: sockets node.js

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

2 个答案:

答案 0 :(得分:4)

看看the documentation for the net module

  

<强> net.connect(arguments...)

     

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

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

除非有理由不这样做,否则你可以使用the request method of the http module来发出HTTP请求。

答案 1 :(得分: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);

您可以通过在终端上运行net轻松安装npm install net模块。

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