search
HomeBackend DevelopmentPHP TutorialPHP simple chat room based on 'server push' technology of HTTP long connection_PHP tutorial

PHP simple chat room based on 'server push' technology of HTTP long connection_PHP tutorial

Jul 21, 2016 pm 03:43 PM
amphttpphpquotIncludebased ontechnologytextserverofchatroomconnectfront page

The first is the homepage, which contains a text input and an iframe that displays chat content, and a hidden iframe used to submit the form:

Copy code The code is as follows:

//chat.php
header('cache-control: private');
header('Content-Type: text/html; charset =utf-8');
?>




< ;form method="POST" target="say" action="./say.php" onsubmit="submitChat(this)">




The other one is to save the chat content submitted by the user. I simply write the text and do not lock it. This is just a simple version:
Copy code The code is as follows:

$content = trim($_POST['content']);
if ($content) {
$fp = fopen('./chat.txt', 'a');
fwrite($fp, $content . "n");
fclose($fp);
clearstatcache();
}
?>

Next let’s look at the main HTTP long connection part, which is the chat_content.php file:
Copy code The code is as follows:

header('cache-control: private');
header('Content-Type: text/html; charset=utf-8');
//The test sets a 30-second timeout, which is usually set for a longer time.
set_time_limit(30);
//This line is to deal with the BT of IE
echo str_repeat(' ', 256);
ob_flush();
flush();
$fp = new SplFileObject('./chat.txt', 'r+');
$line = 0;
$totalLine = 0;
while (!$fp->eof()) {
$fp->current();
$totalLine++;
$fp->next();
}
$fp->seek($totalLine);
$i = $totalLine - 1;
while (true) {
if (!$fp->eof()) {
if ($content = trim($fp->current ())) {
echo '
';
echo htmlspecialchars($content);
echo "
";
flush();
$fp ->next();
$i++;
}
} else {
$fp->seek($i - 1);
$fp->next() ;
}
{
//Here you can add heartbeat detection and exit the loop
}
usleep(1000);
}
?>

Let me explain it line by line, and it is actually easier to understand:
06. Set a timeout. Since you need to maintain a long HTTP connection, this time must be longer, maybe a few hours, as mentioned above The article also explains that only two of these long HTTP connections can be opened due to browser limitations. In addition, 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 timeout. 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. Other browsers may also have settings for other browsers. For details, you can check the description of the frush function in the PHP manual. 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 lines in the file so that the content can be read from the end of this line.
The following while loop is an infinite loop, which loops to output the file content. Each time it is judged whether the end of the file is reached. If a user writes to the file, the current detection is definitely not the end of the file, so the line is read out. Output, otherwise move the pointer forward one line and continue looping, 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 need to be done here. For example, each user keeps a heartbeat flag and updates the last heartbeat time every few seconds. When the last time is detected and has not been updated for a long time, this infinite loop is launched and the HTTP connection is closed.
OK, the basic principle is like this. Of course, the performance is not clear. If you are interested, you can try it yourself. Welcome to communicate.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320705.htmlTechArticleThe first is the homepage, which contains a text input and an iframe for displaying chat content, and a hidden iframe for submission form: Copy the code as follows: ?php //chat.php header(...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)