Chat application AJAX polling

前端 未结 12 1629
天命终不由人
天命终不由人 2020-12-14 20:11

In the project I am currently working on, we have the need to develop a web chat application, not a very complex chat, just a way to connect two people to talk about a very

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 20:52

    I just found this post, it is old, but polling concept gives troubles for a lot of poeple. So i'll put an implementation example here. But before giving it to you, I should give you an advice that made me mad some time ago :

    When you poll, you should take care of sessions behaviour (race conditions). To make it simple : if you open a session, the session file is locked until the session is closed to avoid 2 theads writting different data into it. So, if you need a session to check if a user is logged or so, always close the session before polling.

    My demo gives you an example of a polling implementation in PHP. I will not use a database, but a file instead. When you click polling button, you will enter the loop and until the file is modified, you will stay polling. When you fill the form and click Release, what you typed will be saved into the file. Modification time of the file will change so the polling will stop.

    Tip: use a tool like Firebug to see what's happen.

    Now lets speak in a better langage than my english :

     $time) {
                    $result = htmlentities(file_get_contents('poll.txt'));
                    $poll = false;
                }
    
                // Of course, else your polling will kill your resources!
                $number_of_tries++;
                sleep(1);
            }
    
            // Outputs result
            echo "Number of tries : {$number_of_tries}
    {$result}"; die(); } // Here we catch the release form if (isset($_GET['release'])) { $data = ''; if (isset($_GET['data'])) { $data = $_GET['data']; } file_put_contents('poll.txt', $data); die(); } ?>

    Give me some text here :



    Result after releasing polling :

    You can try it here

提交回复
热议问题