gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:16 25 4
gpt4 key购买 nike

我使用以下代码编写了一个小型 Node.js 服务器“网络”模块。客户端和服务器代码如下所示客户..socket 在全局中声明并由该函数调用。我正在使用第 3 方 API 进行套接字,它可以与 php 或 C++ 套接字配合良好。所以它肯定不是基于 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是一个函数,它根据服务器发送的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 页面发送数据时,数据会发送到服务器并按预期返回,但该过程会重复出现,并且我在双方(我指的是服务器和客户端)上多次收到相同的信息。 .

说。如果我从客户端发送“hello”,它会从服务器在客户端收到 2-3 个“hello”。我刚刚注意到的一个重要问题是每次我向服务器发送数据时,递归次数都会增加。

有人知道出了什么问题吗?

最佳答案

每次执行外部 on('data' ... 时,都会添加另一个 on('data' ... 元素;这就是为什么您在每个请求中获得的数量都会增加。您正在修改处理程序结构以在处理程序中添加处理程序。

关于html - Node.js,数据在服务器和客户端之间来回循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6818424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com