我有一个简单的节点js服务器,我想连接到另一个套接字,读取数据,然后将其返回给客户端。

http.createServer(function(req, res){
     var sock = new Socket();
        sock.connect(80, "www.google.com", function(){
            console.log("Connected to google..");
            sock.write("GET /\r\n\r\n");
        });
        sock.on("data", function(data){
            console.log(data.toString());
            res.writeHead(404, {"Content-type": "text/plain"});
            res.write(data, "binary");
            res.end();
            sock.end();
        });
        sock.on("end", function(){
            console.log("Disconnected from socket..");
        });
}, 8080);


但这显然不起作用,因为对数据回调的调用是异步的。

那么,如何使用节点js完成此操作?

最佳答案

添加缺少的“ require”语句和server.listen()调用以使脚本运行后,它对我来说很好用:

var http = require('http');
var Socket = require('net').Socket;
var server = http.createServer(function(req, res){
     var sock = new Socket();
        sock.connect(80, "www.google.com", function(){
            console.log("Connected to google..");
            sock.write("GET /\r\n\r\n");
        });
        sock.on("data", function(data){
            console.log(data.toString());
            res.writeHead(404, {"Content-type": "text/plain"});
            res.write(data, "binary");
            res.end();
            sock.end();
        });
        sock.on("end", function(){
            console.log("Disconnected from socket..");
        });
});
server.listen(8080);

07-26 02:31