Check if user is on page

前端 未结 2 1138
刺人心
刺人心 2021-01-16 22:22

I\'m building a one on one chat application that allows users to host rooms. Just to give a little more feedback:

  1. User creates room (rooms are public, anybo

2条回答
  •  旧巷少年郎
    2021-01-16 23:21

    assume you have 5 people in the room (and one or more are bound to be active), do these:

    • for every action a user takes (be it a keystroke or an actual message sending), "ping" the server (send it a message that you exist) and log it (in your database perhaps) the the time that event took place. (notice how facebook has that "User is typing..." - this is it.

    • in turn for sending that action (via ajax i suppose), the reply of the server is a list of users in that room that are online and not online. do this by comparing the current time with the time of last activity for each user inside (current time - last active time = time away)

    • knowing who's online and not, rebuild the "chat mate list" in your browser

    you can do a multitude of possibilities. like say allow 5 minutes or else, that user is idle. if the difference in time 15 minutes or more, consider that person off.

    you can also take a step further by pinging the server for an update on who's online regularly, otherwise called a "heartbeat" instead of having to do it by keystroke or every message send. procedure it the same: tell the server you are online, log your existence, and have it return a list of chat mates.

    do note that in this application (browser chat), there is no way that the server knows that you are offline, closed your browser etc. that's why you need that "heartbeat" as well as logging your actions regularly.

    as for host... you should tag that room with the host id and the heartbeat will tell you if he's still online.

提交回复
热议问题