套接字在nodejs中

我需要在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服务器上面做的事情?

看一下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(data); }); 

没有任何价值的是,除非有一个原因,否则可以使用http模块的request方法发出HTTP请求。

在NodeJS中,我们有一些socket编程模块,但最stream行的是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); 

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

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