Nik*_*kis 4 javascript ajax setinterval session-storage long-polling
我使用以下方法开发了一个javascript聊天(后端的php):
1) long-polling to get new messages for the receiver
2) sessionStorage to store the counter of messages
3) setInterval to read new messages and if sessionStorageCounter < setIntervalCounter then the last message is shown to receiver.
4) javascript to create,update and write the chat dialogues
Run Code Online (Sandbox Code Playgroud)
该模块工作正常,但当用户快速聊天时,接收者的前端会收到两到三条相同的消息,(计数器都不会失败,查询也不会提供双重插入).
代码似乎是正确的(这就是我不提供代码的原因),因此间隔延迟可能是原因(在减少间隔延迟时,没有任何变化).
您是否认为上述架构是一种不好的做法,您认为哪种架构可以消除错误?
我的方法,如果我自己解决(而不是使用已经处理过这个的现有库)将是:
如果重新生成确实导致从服务器到客户端传递重复项,则每条消息上存在唯一ID会使消除它们变得微不足道.将服务器端消息队列视为事件流,每个客户端都跟踪其最后读取位置.客户端没有猜测消息的正确顺序,有多少等等 - 因为它的状态完全由"我看到了什么"组成,很少有机会失去同步.