Home Backend Development PHP Tutorial PHP server push technology chat room

PHP server push technology chat room

Jul 25, 2016 am 08:57 AM

  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 of this Website
    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

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

    JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

    How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

    Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

    What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

    The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

    Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

    The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

    How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

    How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

    How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

    Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

    How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

    How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

    See all articles