同步连接到节点js中的套接字

时间:2013-06-27 01:21:37

标签: javascript node.js

我有一个简单的节点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实现这一目标呢?

1 个答案:

答案 0 :(得分:0)

添加缺少的“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);