How to feed real-time notifications while logged in?

Asked

Viewed 570 times

3

I’m looking for a system that keeps updating the logged in user to show the messages he receives. Considering that this system will have 250-500 simultaneous users, what is the best way to search the data in the database and update the user’s message box? I thought about running a script every minute and updating everyone logged in but I don’t know if this is the best way. I intend to do this via Ajax with setInterval but I am open to ideas since I never did and I do not know what the best implementation.

What worries me is server overload!

inserir a descrição da imagem aqui

  • 3

    Long Poling or Websocket or Ajax.

  • @Gumball can explain me a little bit about the functioning of these technologies?

1 answer

2

When it comes to an application developed for the web, there is no way out. The only ways to create updates for the client are:

Create business rules on the client’s own computer (Solution in case the client will perform an activity on their own machine, such as being alerted after filling out a form correctly or performing a parse of a file via js).

Hit the server via ajax, requesting and handling the received data. (I believe this should be your approach)

Okay, but what about "weigh on the server"?

The proposal of ajax is to minimize the amount of data traffic, in order to perform small requests to the server and take advantage of the data already provided. Then the solution would be to create an endpoint to search only the necessary data. Example:

Client’s computer performs the request:

$.ajax({
    type: "POST",
    url: "/checkUpdates",
    data: {
        userId: 1,
        lastMessageId: 1
    },
    dataType: "json",
    success: function(response) {
        verifyAjaxReponse(response);
    }
});

You collect the data sent by the user, and compare them with the received:

$data = json_decode($params); //dados vindos pelo ajax
$result = $db->exec('select lastMessageId where userId = "' . $data['userId'] . '"');

if ($data['lastMessageId'] == $result['lastMessageId']) { //Supondo que a request não passe por aqui, e exista um novo resultado
    $result == false;
}
$framework->disableLayout();
$framework->view = json_encode($result); // $result = ['message' => 'Você recebeu uma nova mensagem. Verifique sua caixa de entrada', 'id'];

After that, the data will be minified and returned to the client’s machine, where your javascript will be able to verify if the Response has any update and generate the alert.

success: function(response) {
    verifyAjaxReponse(response);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.