Jump to content

How to detect if a user is online?


NorKayak
 Share

Go to solution Solved by Psycho,

Recommended Posts

I have a general question. Just need to be put on the right direction.

 

I made that little game I put on a server. Now I wish that 2 persons could play against each other online. So I made a signup/login and I can list all the users against which you would like to play. Now how could I know who is actually online and send him/her an alert when it is his/her turn to play?

 

My first idea was to send emails every time it's a player turn to make a move; but there must be something more elegant to do in-game?

 

I'm having a lot of fun coding that thing and any help would be great 🙂

Link to comment
Share on other sites

14 minutes ago, DanEthical said:

Have you tried with a Modal or JS alert?

Probably use a Session or Cookie to determine who is online?

I know a little about session and cookie but how can I use that to know if a user is actually online and interact with him?

Link to comment
Share on other sites

A Session var won't work since each player has a separate session.  A cookie could work but a table entry as described in the article from DanEthical would work better.  Assuming that you already have some kind of players table storing info about him/her, you could simply add a logged-on field to that table and turn it on when the user logs in.  Along with that you need a field that records the last time the user interacted with the system.  Every time that a user hits a page of the app, you would need to just update his players record with the current time.  Then a check for who is currently on would simply be a query for records with the logged-on field set and having a recent time which is determined by you, the designer.

Link to comment
Share on other sites

  • Solution

With a web application, you can certainly record when a user logs in, but even if you have a logout function a user can simply close the browser window. So, you do need a way to track that they are still there. Since this is a game where two people are playing each other, I think you need to do more than just track when they hit a new page. Here is what I would do:

  1. Create a last active field in the user table. Every time you see activity from the user, update the timestamp.
     
  2.  Determine "how long" of a time period that you would consider someone as still active: 5 minutes, 10 minutes, ??? Then use that time period to query for active players based on those whose last active timestamp is within the last X minutes. This can also be used for two players already in a game to notify one that the other has dropped off.
     
  3. Once two users start a game use AJAX to both continually update their last active value AND to proactively notify them of anything relevant. E.g. when it is their turn, if the other user drops off, etc. AJAX is simply javascript that makes a server call and returns back data to the user which you can then implement additional logic to act on that returned data. You can update the content in their browser window based on the move the other player made, make a notification, whatever. In this case, I would have the AJAX make a call every X seconds (10, 20, 30 ???). That call would do several things:
    • Update the last active timestamp for the user
    • Check if the other user is still active. Since the other player will also have AJAX running, their last active timestamp should never be greater than the time you set for the AJAX calls to be made. So, if the other players last active timestamp is more than double that time period, I would let the user know that the other user has dropped
    • Check if the other user has made a move (if it was their turn). If so, alert the user that the other user has made their move, show the results of that move, and tell the player it is now their turn.

I'm sure there are some things I am leaving out, but the core of it is to use regular calls via AJAX to determine when users have completed a turn and to ensure they are still online. Be sure to use a JavaScript framework to do this (such as JQuery) instead of trying to build the AJAX code with native JavaScript.

Link to comment
Share on other sites

Actually using Fetch in Vanilla JavaScript is pretty easy to do: (Here's an example)

    /* Success function utilizing FETCH */
    const sendUISuccess = function (result) {
        //console.log('Result', result);
        if (result) {
            d.querySelector('#recaptcha').style.display = "none";
            submit.style.display = "none";
            notice.style.display = "grid";

            notice.textContent = "Email Successfully Sent!";
            notice.style.color = "green";
            message.style.display = "grid";
            //messageSuccess.style.display = "block";
            d.querySelectorAll('form > *').forEach(function (a) {
                a.disabled = true;
            });
        }
    };

    /* If Database Table fails to update data in mysql table */
    const sendUIError = function (error) {
        console.log("Database Table did not load", error);
    };

    const handleSaveErrors = function (response) {
        if (!response.ok) {
            throw (response.status + ' : ' + response.statusText);
        }
        return response.json();
    };

    const saveRequest = (sendUrl, succeed, fail) => {

        fetch(sendUrl, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(sendEmail)

        })
            .then((response) => handleSaveErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
    };

though jQuery has jQuery.get() I believe which is the same thing as Fetch in Vanilla JavasScript which might be worth looking into? In my opinion it easier and coding is more logical.   I like that you don't have to worry about parsing the data and handling errors is easy to do. In your case you could make a fallback option or tell the other player that the other person is no longer online.

Edited by Strider64
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.