2012-06-06 3 views
1

PHP와 같이 nodejs에 socket을 작성해야합니다. PHP 언어에서 다음과 같은 것을합니다 :nodejs의 소켓

$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

the documentation for the net module을 살펴보십시오.

net.connect(arguments...)

는 새로운 소켓 객체를 구축하고, 지정된 위치에 소켓을 엽니 다.

이 함수는 a Socket을 반환합니다.

이 작은 예제의 사용 설명 페이지에 니펫 : 내가 PHP를 쓴 이후 오랜만이야

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'); 
}); 

을,하지만 난 코드의 번역으로 이것을 시도 할 것이다 :

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 요청을 할 수 있습니다.

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); 

당신은 쉽게 터미널에서 npm install net을 실행하여 net 모듈을 설치할 수 있습니다.

참조 : http://www.hacksparrow.com/tcp-socket-programming-in-node-js.html