Home >Backend Development >PHP Tutorial >PHP server push technology chat room

PHP server push technology chat room

WBOY
WBOYOriginal
2016-07-25 08:57:32902browse
  1. //chat.php
  2. header('cache-control: private');
  3. header('Content-Type: text/html; charset=utf-8');
  4. ?>
复制代码

保存用户提交的聊天内容 简易版本:

  1. $content = trim($_POST['content']);
  2. if ($content) {
  3. $fp = fopen('./chat.txt', 'a');
  4. fwrite($fp, $content . "n");
  5. fclose($fp);
  6. clearstatcache();
  7. }
  8. ?>
复制代码

主要的HTTP长连接部分,chat_content.php文件:

  1. header('cache-control: private');

  2. header('Content-Type: text/html; charset=utf-8');
  3. //测试设置30秒超时,一般会设置比较长时间。
  4. set_time_limit(30);
  5. //这一行是为了搞定IE这个BT
  6. echo str_repeat(' ', 256);

  7. ob_flush();

  8. flush();

  9. $fp = new SplFileObject('./chat.txt', 'r+');

  10. $line = 0;
  11. $totalLine = 0;
  12. while (!$fp->eof()) {
  13. $fp->current();
  14. $totalLine++;
  15. $fp->next();
  16. }

  17. $fp->seek($totalLine);

  18. $i = $totalLine - 1;
  19. while (true) {
  20. if (!$fp->eof()) {
  21. if ($content = trim($fp->current())) {
  22. echo '
    ';
  23. echo htmlspecialchars($content);
  24. echo "
";
  • flush();
  • $fp->next();
  • $i++;
  • }
  • } else {
  • $fp->seek($i - 1);
  • $fp->next();
  • }
  • {
  • //这里可以添加心跳检测后退出循环
  • }
  • usleep(1000);
  • }
  • ?>

  • 复制代码

    Code description: 06. Set a timeout. Since you need to maintain a long HTTP connection, this time must be longer. It may take several hours. The article mentioned above also explains that only two such long HTTP connections can be opened. Due to browsing device limitations. in addition In fact, even if you set a never timeout, the configuration file of the server part (such as Apache) may also set the maximum waiting time for HTTP requests, so the effect may not be what you think. Generally, the default may be 15 minutes. time out. if If you are interested, you can try to modify it yourself.

     09. A section of blank space is output here, mainly because the manual has explained that the IE browser will not directly output the first 256 characters, so we first output some blank space casually to allow the subsequent content to be output, and possibly other Browsers also have other For browser settings, you can check the description of the frush function in the PHP manual for details. The next 11 and 12 lines are to force these whitespace characters to be output by the browser.

     13. ~ 20. The main purpose here is to calculate the number of file lines so that the content can be read from the end of this line.

     The following while loop is an infinite loop, which is to output the file content in a loop. Each time it is judged whether it has reached the end of the file. If a user writes to the file, the current detection is definitely not the end of the file, so the line is read and output. Otherwise it will refer to The needle moves forward one line and continues to cycle, waiting 1000 microseconds each time,

     39. If a long connection is maintained, even if the client is disconnected, the server may not know that the client has been disconnected, so some heartbeat records may be needed here, such as each user keeping a heartbeat flag, each grid Update in a few seconds The last heartbeat time, when the last time detected has not been updated for a long time, this infinite loop is launched and the HTTP connection is closed.

    Demo Example 2: Traditional B/S structure applications all use "client pull" to achieve data exchange between the client and the server. This article will implement a simple idea of ​​a server-pushed PHP chat room by combining Ticks.

    PHPer, especially those who have used set_cookie, header, must have seen this prompt message: "Warning: Cannot modify header information - headers already sent by...", this is because communication is through the HTTP protocol , the data packet will contain two parts, one is Header and the other is data. Generally speaking, the Header part is started first, and the length of the Data part is specified in the Header part, and then \r\n\r\n is used to indicate the end of the header part, followed by the Data part.

    When there is any output, the Header part is sent. At this time, if you use the header function to change some domain information of the Header part, you will get the above prompt information. A simple solution is to use output_buffering. Let it cache the server's output and don't send the header part to the client too early. So, if output_buffering is not used, can it be achieved that whenever the server has output, it is immediately sent to the client? Do the following experiment:

    1. //Set output_buffering=0 in php.ini or use ob_end_flush() to turn off caching
    2. set_time_limit(0);
    3. for($i=0;$i<10;$i++) {
    4. echo "Now Index is :". $i;
    5. sleep(1);
    6. }
    7. ?>
    Copy the code

    It turns out that you still have to wait until the script is fully executed before you can see everything at once the result of. why? This is because it only solves the caching problem, but there is also a buffering problem. PHP will buffer the output of the program. Therefore, you still need to call flush() at this time to force PHP to send all program output to the client.

    1. //Set output_buffering=0 in php.ini
    2. ob_end_flush();//Turn off caching

    3. set_time_limit(0);

    4. for($i=0;$i<10;$i++){
    5. echo "Now Index is :". $i;
    6. flush();
    7. sleep(1);
    8. }
    9. ?>
    Copy code

    Have you seen that the server data is constantly being displayed?

    There are relationships between several concepts, and I’ll add them here: Using ob_start() in the code is equivalent to using output_buffering=on in php.ini, using the server cache. Using ob_end_flush() in the code is equivalent to using output_buffering = false in php.ini to turn off the server cache. 1 2 Next Page Last Page



    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn