A
A
Alexey Chertok2018-05-29 14:03:10
PHP
Alexey Chertok, 2018-05-29 14:03:10

How to implement PHP + MYSQL + JAVASCRIPT long polling?

Hello. Faced with a direction with which it was not necessary to work before. I would like to understand the long polls.
I am writing a small php + mysql + javascript chat. At the moment, I have put short requests in order to receive messages. But the very fact that the request is sent every two seconds to the server now does not suit me at all.
I have climbed a bunch of forums, read a bunch of documentation, but almost all of them are related to how to implement this method not using php + mysql, but by reading txt files.
Can you please tell me how to implement this method using php + mysql ?
Libraries like socket.io, comet servers don't offer. I see no reason to use them if you can do everything in its purest form without unnecessary libraries. Moreover, javascript and php allow you to do this.
For example, what I have.
The message table is built like this:

CREATE TABLE IF NOT EXISTS `messages_elements` (
  `id` smallint (5) unsigned NOT NULL auto_increment,
  `user` SMALLINT(5) NOT NULL,
  `text` TEXT NOT NULL,
  `date` TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
  PRIMARY KEY  (`id`),
  KEY (`user`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

I send messages using xhr from the javascript side, and using insert from the mysql side.
After, I get the messages themselves from the base with an array and break it up using while, example:
$database = "SELECT * FROM messages_elements ORDER BY `date` ASC";
$query = $this->DB->query($database);

 while ($message = $this->DB->fetch_array($query)){
    $data = array(
        'id' => $message['id'],
        'user' => $message['user'],
        'text' => $message['text'],
        'date' => $message['date']
    );
}

Well, in the end, I drive everything into JSON format and, using xhr, I display it in a block using innerHTML. Can you please tell me how can I implement a long request with my method? I will be very grateful.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Justique, 2018-05-29
@Justique

https://socket.io/

A
Andrey Shatokhin, 2018-05-29
@Sovigod

Historically, long polling and websocket are not friends with php. The sad thing is that php has never been a web server itself, and therefore it does not know how to manage the connection well. Usually there is some kind of layer between the client and php - nginx / apache / etc.
Of course there are options. There is a native dev-web server in php. There are implementations like php-pm. But as a web server - any of them is inferior to nginx / apache.
I would generally prohibit pulling long polling on apache+mod_php/nginx+php-fpm. This requires more resources than requests every 2 seconds.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question