问题
I have used an EventSource method to get online status of active users on my website. In this following JavaScript code is inserted in every page
var source = new EventSource("set_online.php");
Thus this code is executing set_online.php
file continuously.
On server side i.e. in set_online.php
following code executed
$query = "UPDATE my_db SET last_active = '{$current_time}' WHERE id = {$_SESSION["id"]}";
$result = mysqli_query($connection, $query);
Now I have two concerns about this:
- As Database is updating last_active continuously in realtime, will it affect server load?
- As connection is open as long as user is on website, will it create vulnerabilities?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/44342431/is-it-reliable-to-use-eventsource-to-get-users-online-status