2013-03-06 3 views
3

노드에서 stackoverflow 및 new에서 새로 추가되었습니다.노드 JS 실행 된 함수 두 번

하나의 간단한 소켓 서버와 하나의 웹 서버가 있습니다.

누군가 웹 서버에 연결되어 있으면 웹 서버가 소켓 서버에 메시지를 보내길 원합니다.

브라우저 < => 웹 서버/소켓 클라이언트 < => 소켓 서버

나는이 같은 서버 생성

: 소켓 서버로 메시지를 전송

var http = require('http'); 
var net = require('net'); 
var HOST = '192.168.1.254'; 
var PORT = 8888; 
var client = new net.Socket(); 

http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello World\n', function(){ 
     client.connect(PORT, HOST, function() { 
     console.log('Connected To: ' + HOST + ':' + PORT); 
     client.write('0109001' + "\n"); 
     }); 

    // Add a 'data' event handler for the client socket 
    // data is what the server sent to this socket 
     client.on('data', function(data) { 
      console.log('The Data: ' + data); 
      client.destroy(); 
     }); 

     // Add a 'close' event handler for the client socket 
     client.on('close', function() { 
      console.log('Connection closed'); 
     }); 
    }); 
}).listen(1337, '127.0.0.1'); 
console.log('Server running at http://127.0.0.1:1337/'); 

이 코드는 작동하지만 웹 서버를 두번. 콜백 또는 무언가에 문제가 있습니까? 도움이 될 것입니다.

+1

한 번만 요청을 보내시겠습니까? 모든 브라우저가하는 favicon 요청을 잊지 마십시오. – pfried

+1

['console.log (req.url);'] (http://nodejs.org/api/http.html#http_request_url)을 추가하십시오. 매번 동일한 URL을 출력합니까? –

답변

6

을 당신이 서버에이 개 요청을 보내는 브라우저에이 코드를 호출하는 경우. 하나는 FavIcon 용이고 다른 하나는 페이지 자체 용입니다.

요청이 2 개이기 때문에 콜백 내부의 코드가 두 번 호출됩니다.

Matt가 말한 것처럼 : 콜백 내에 소켓 응답 핸들러를 놓지 마십시오. 당신이 그들에 대한 참조를 잃어 버리고 모든 요청에 ​​대해 새로운 핸들러가 첨부되기 때문입니다.

var http = require('http'); 
var net = require('net'); 
var HOST = '192.168.1.254'; 
var PORT = 8888; 
var client = new net.Socket(); 
var url = require('url'); 

http.createServer(function (req, res) { 
    console.log(url.parse(req.url)); 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello World\n', function(){ 

     console.log('Connected To: ' + HOST + ':' + PORT); 

    }); 
}).listen(1337, '127.0.0.1'); 
console.log('Server running at http://127.0.0.1:1337/'); 
+0

다음은 favicon 요구 사항, 적어도 디버깅하는 동안 : https://gist.github.com/kentbrew/763822 –

+0

favicon에 대한 올바른지, 브라우저의 http 헤더가 favicon 요청을 포함한다는 것을 잊었습니다. 어쨌든, 참조 문제에 대해 지적 해 주셔서 감사합니다. – BigBoss

0

client.on() 콜은 res.end() 콜백 안에 있으면 안되며, 이는 이벤트 핸들러가 여러 번 연결되는 원인이됩니다. 즉, 데이터가 수신 될 때마다 여러 번 호출됩니다.

대신을 시도해보십시오

http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello World\n', function(){ 
     client.connect(PORT, HOST, function() { 
     console.log('Connected To: ' + HOST + ':' + PORT); 
     client.write('0109001' + "\n"); 
     }); 
    }); 
}).listen(1337, '127.0.0.1'); 

// Add a 'data' event handler for the client socket 
// data is what the server sent to this socket 
client.on('data', function(data) { 
    console.log('The Data: ' + data); 
    client.destroy(); 
}); 

// Add a 'close' event handler for the client socket 
client.on('close', function() { 
    console.log('Connection closed'); 
}); 
+1

이것이 문제가 확실합니까? 모든 요청에 ​​첨부 된 것 같습니다. 그것은 좀비 처리기입니다,하지만 난 그게 소켓에 연결하는 다른 서버에 2 요청의 문제를 일으키는 것 같아 – pfried

+0

@ pfried 나는 당신이 맞을지도 모른다 생각 ... 지금 당신이 그것을 언급 소켓, 것 같습니다 client.write() 줄에만 쓰여졌습니다 –

+0

브라우저의 http 헤더가 favicon 요청을 포함한다는 것을 잊었습니다 :) 콜백 외부에 이벤트 처리기를 배치하도록 나를 안내해 주셔서 감사합니다. – BigBoss