繁体   English   中英

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

[英]Synchronously connecting to a socket in 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);

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

那么,如何使用Node 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM