2013-05-19 4 views
0

나는 TCP 연결과 node.js를 사용하여 간단한 대화방을 만들고 있습니다. 나는 "Enter"뒤에 텍스트가 전송되기를 기대하지만, 대신에 각 문자가 눌러 진 후에 바로 문자가 전송된다는 것이 일어난다. 다음은 내 코드입니다 ...node.js의 클라이언트에서 서버로 데이터 전송

var server = net.createServer(function(conn){ 
    console.log('\033[92m new connection! \033[39m'); 
    conn.write('> welcome to \033[92mnode-chat\033[39m! \n' 
    + '> ' + count + ' other people are connected at this time.' 
    + '\n > please write your name and press enter: ' 
); 

    count ++; 
    conn.setEncoding('utf8'); 
    conn.on('data', function(data){ 
     console.log(data); 
    }); 

    conn.on('close', function(){ 
     count --; 
    }); 
}); 
+0

코드를 클라이언트 측에 표시 할 수 있습니까? –

+0

텔넷을 클라이언트로 사용하고 있습니다. – Misaki

답변

1

텔넷은 자체 TCP 요청으로 각 문자를 전송합니다.
각 연결에서 생성 된 소켓에서 수신 대기하는 다른 방법을 사용하는 것이 좋습니다. 앞으로이 방법을 사용하면 지루한 중앙 위치가 아닌 각 소켓을 자체적으로 관리 할 수 ​​있습니다.

var server = net.createConnection(... 
    ... 
}); 
server.on('connection', function(socket, connection){ 
    //I'm adding a buffer to the socket although you might not need it (try to remove it and see what happened) 
    socket.buf = ''; 
    var self = this; //Use it if 'this' does not work. (explanation why to do it will confuse here but if there is a need I will explain) 
    //Create a listener for each socket 
    socket.on('data', function(data){ 
    //Since telnet send each character in it's own we need to monitor for the 'enter' character 
    if((data=='\\r\\n') || (data=='\\n')){ 
     console.log(this.buf);//If 'this' doesn't work try to use 'self' 
     this.buf = ''; 
    } 
    else //No 'enter' character thus concat the data with the buffer. 
     this.buf += data; 
    }); 
    socket.on('end', function(){ 
    //Socket is closing (not closed yet) so let's print what we have. 
    if(this.buf && (this.buf.length > 0)) 
     console.log(this.buf); 
    }); 
}); 
관련 문제