2013-05-19 150 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

我使用Telnet作爲我的客戶端。 – Misaki

回答

1

這聽起來是telnet發送每個字符由自己的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); 
    }); 
}); 
相關問題