簡體   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