Simple php Chat Room Based on HTTP persistent connection & quot; server push & quot; Technology

Source: Internet
Author: User

First, the homepage contains a text input and an iframe that shows the chat content, and a hidden iframe used to submit the form:
Copy codeThe Code is as follows:
<? Php
// Chat. php
Header ('cache-control: private ');
Header ('content-Type: text/html; charset = UTF-8 ');
<Script type = "text/javascript">
Function submitChat (obj ){
Obj. submit ();
Document. getElementsByName ('content') [0]. value = '';
<Iframe src = "./chat_content.php" height = "300" width = "100%"> </iframe>
<Iframe name = "say" height = "0" width = "0"> </iframe>
<Form method = "POST" target = "say" action = "./say. php" onsubmit = "submitChat (this)">
<Input type = "text" size = "30" name = "content"/> <input type = "button" value = "say" onclick = "submitChat (this. form) "/>

The other is to save the chat content submitted by the user. I simply wrote the text and did not lock it. This is just a simple version:
Copy codeThe Code is as follows:
<? Php
$ Content = trim ($ _ POST ['content']);
If ($ content ){
$ Fp = fopen ('./chat.txt', 'A ');
Fwrite ($ fp, $ content. "\ n ");
Fclose ($ fp );
Clearstatcache ();

Next, let's take a look at the main HTTP persistent connection section, that is, the chat_content.php file:
Copy codeThe Code is as follows:
<? Php
Header ('cache-control: private ');
Header ('content-Type: text/html; charset = UTF-8 ');
// Set the test time-out to 30 seconds. Generally, a relatively long time is set.
Set_time_limit (30 );
// This line is used to handle the BT
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 '<div> ';
Echo htmlspecialchars ($ content );
Echo "</div> ";
Flush ();
$ Fp-> next ();
$ I ++;
} Else {
$ Fp-> seek ($ I-1 );
$ Fp-> next ();
// You can add a heartbeat check and exit the loop.
Usleep (1000 );

I will explain it in one line, but it is easier to understand:
06. set a time-out period. To maintain a long HTTP connection, this time must be relatively long. It may take several hours, as described in the above article, this type of HTTP persistent connection can only open two because of browser restrictions. In addition, even if you set a configuration file that never times out, the configuration file on the server (such as Apache) may also set the maximum waiting time for the HTTP request, therefore, the effect may not be what you think. Generally, the timeout may be 15 minutes by default. If you are interested, try to modify it.
09. A blank section is output here, which is explained in the manual. The IE browser will not directly output the first 256 characters, so we can output some blank spaces at will first, in order to let the following content output, other browsers may also have settings for other browsers. For details, refer to the description of the frush function in the PHP manual. Next Lines 11 and 12 are forced to throw these blank characters to the browser for output.
13 .~ 20. This is mainly used to calculate the number of file lines so that the content can be read from the end of this line.
The next while loop is an endless loop, that is, the content of the output file. Each time you determine whether the object has reached the end, if a user writes a file, the current detection is definitely not the end of the file, read the row and output it. Otherwise, move the Pointer Forward to a row and continue the loop. Wait for 1000 microseconds each time,
39. if you keep persistent connections, the server may not necessarily know that the client is disconnected even if the client is disconnected. Therefore, you may need to make some heartbeat records, such as keeping a heartbeat flag for each user, the last heartbeat time is updated several seconds per cell. When the last heartbeat time is not updated for a long time, this endless loop is launched to close the HTTP connection.
OK, the principle is basically like this. Of course, this performance is unclear. If you are interested, try it. Please feel free to contact us.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.