IT Share you

Node.js net에서 pipe () 사용

shareyou 2020. 11. 24. 20:36
반응형

Node.js net에서 pipe () 사용


net 모듈에 pipe대한 여러 Node.js 예제에 표시된 함수를 둘러싼 문제가 있습니다.

var net = require('net');

var server = net.createServer(function (socket) {
  socket.write('Echo server\r\n');
  socket.pipe(socket);
});

누구든지 이것이 어떻게 작동하며 왜 필요한지에 대한 설명을 제공 할 수 있습니까?


pipe()함수는 사용 가능 해지면 읽을 수있는 스트림에서 데이터를 읽고 쓰기 가능한 대상 스트림에 씁니다.

문서의 예는 수신 한 것을 보내는 서버 인 에코 서버입니다. socket는 따라서 데이터가 기입되도록 구현 객체 모두 읽고 쓸 스트림 인터페이스는 다시 소켓 수신한다.

이는 pipe()이벤트 리스너 를 사용하는 메서드를 사용하는 것과 같습니다 .

var net = require('net');
net.createServer(function (socket) {
  socket.write('Echo server\r\n');
  socket.on('data', function(chunk) {
    socket.write(chunk);
  });
  socket.on('end', socket.end);
});

pipe()읽기 가능한 스트림에서 읽고 쓰기 가능한 스트림에 씁니다. 마치 Unix 파이프와 비슷합니다. 오류, 파일 끝, 한쪽이 뒤쳐지는 경우 등 모든 "합리적인"작업을 수행합니다. 특정 예제는 socket읽기와 쓰기가 모두 가능 하기 때문에 약간 혼란 스럽습니다 .

이해하기 쉬운 예는 http 요청에서 읽고 http 응답에 쓰는 이 SO 질문 에 있습니다.


다음 요청 핸들러를 고려하십시오.

var server = http.createServer(function(req, res){
     console.log('Request for ' + req.url + ' by method ' + req.method);
    if(req.method == 'GET'){
        var fileurl;
        if(req.url == '/')fileurl = '/index.html';
        else {
            fileurl = req.url;
        }
    }
    var filePath = path.resolve('./public'+fileurl);
    var fileExt = path.extname(filePath);
    if(fileExt == '.html'){
          fs.exists(filePath, function(exists){
        if(!exists){
          res.writeHead(404, {'Content-Type': 'text/html'});
          res.end('<h1>Error 404' + filePath + 'not found </h1>');
          //the end() method sends content of the response to the client
          //and signals to the server that the response has been sent
          //completely
          return;
        }
        res.writeHead(200, {'Content-Type':'text/html'});
        fs.createReadStream(filePath).pipe(res);
      })
    }
}

fs.createReadStream메서드는 주어진 파일 경로 ( public/index.html) 에서 파일을 읽고 클라이언트보기에 대한 pipe()응답 ( res)에 씁니다 .


There are 2 sockets per Server-Client Connection (2 endpoints). Socket binds IP Address:Port Number. The client gets assigned random port numbers, while the server has dedicated port number. This is the basic explanation of how socket works.

Piping is reserved for redirecting a readable stream to a writable stream.

What socket.pipe(socket) does? It redirects all the data from the readable stream (server) to the writable stream (client). We can tweak this by adding event listeners as @hexacyanide has pointed out.

참고URL : https://stackoverflow.com/questions/20085513/using-pipe-in-node-js-net

반응형