Is it reliable to use EventSource to get User's online status?

为君一笑 提交于 2019-12-06 00:27:49

SSE is not suitable for this purpose - or at least is not designed for it. SSE is a constant stream of events from server to browser.

Your script will work, though. The PHP script will do one thing (update the database) then exit. When it exits the connection is closed. The browser will see the connection has died, and after a few seconds will reconnect again. When the cycle repeats.

Regarding your two questions: 1. It is not really continuous, more a re-connect every 3 seconds. The server load might be significant. 2. The connection is not open continuously; but if it was it does not create any new vulnerabilities.

I would use an ajax call, on a JavaScript interval, instead of SSE. These advantages:

  • Older technology, so wider browser support
  • Explicit control over the timer interval, so you can control the balance between latency and server load.

Your solution is heavy and unnecessary, a better solution would be to reverse the idea and let the server push user status information to your clients.

You can achieve this by implementing sockets using libraries such as socket.io. It's quite simple to achieve and is a more scalable solution.

Basically, when the page is loaded, a connection will be made between your client and the server and when the server wants to communicate with clients he can simply emit an event such as user-status for example.

Your clients can simply listen to this event and update their views accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!