Node.js,数据在服务器和客户端之间来回循环

我用“net”模块编写了一个小型的node.js服务器。 客户端和服务器代码如下所示Client ..套接字在全局声明并由此函数调用。 我正在使用第三方API的套接字可以很好地使用PHP或C ++ socket.so它肯定不是一个基于API的错误。

function SocketAPI() { socket.onConnect = function(success) { if(success) { Connected = true; }else{ alert("Failed to connect to server!"); } } socket.onClose = function() { alert("Connection lost to server!"); } socket.onData = function(text) { if(text==">Send_AuthenTication") { // Tells the client to send authentication data if(localStorage.ID) { socket.send(">"+localStorage.ID); //encrypted }else{ socket.send("<"); } }else if(text.substr(0,2)==">>"){ // User inforamation accept and apply it Packet = JSON.parse(text.substr(2,text.length-2)); while(Users.length){ // users is an array which contains other peers connected to the server Users.pop(); } me = Packet; me.Prepare(); Users.push(me.NameBOX); Usrlst.ShowTab(0); // Now make the socket only listen for output buffer. socket.onData = function( Data ){ //alert(Data); setTimeout( Jparse,100, Data ); } } } socket.connect('localhost',1337);// makes connection } 

其中Jparse是一个函数,它parsing服务器发送的json,并使用socket.send(input)发送数据。

和服务器看起来像这样::

..

  var server = net.createServer(function(socket){ socket.setEncoding('utf8'); socket.Peer = new Client(); socket.on('data',function(Data){ if(Data[0]==">") // this tells that the request is authentication event { // Loads from Pool }else if(Data[0]=="<"){ NewUSER(this.Peer); // Makes new user } this.write(">>"+JSON.stringify(this.Peer)+"\0","utf8",function(){}); this.on('data',function(Data){ console.log(Data); this.write(Data,'utf8',function(){}); }); }); socket.on('end',function(){ console.log("Connection End"); }); // Socket Closed by client/errors socket.on('close',function(error){ console.log("Connection is closed by Had errors?:"+error); }); // Handshake started socket.on("connect",function() { // add server connection in here aha we now have a new user. sys.puts("Connection from"+ socket.remoteAddress); this.write(">Send_AuthenTication\0",'utf8',function(){}); }); }); // starting the server. server.listen(1337,"localhost"); 

当我发送数据使用客户端的HTML页面的数据到服务器,并回来,因为它应该但过程变得经常性,我得到相同的接收更多,然后一边两边我的意思是服务器和客户端..

说。 如果我从客户端发送“你好”,它会从服务器端接收到客户端的2-3个“hello”。我刚刚注意到的一个导入事件是每次向服务器发送一个数据时递增的recursion次数。

任何人都知道什么是错的线索?

每次你执行外部on('data' ... ,你on('data' ...元素on('data' ...添加另一个on('data' ... ,这就是为什么你在每个请求中获得增加的数字。结构来添加处理程序在您的处理程序。