Home Backend Development PHP Tutorial PHP simple chat room based on 'server push' technology of HTTP long connection

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

Jul 29, 2016 am 08:41 AM
http

For the technical principle of "server push" for HTTP long connections, you can check out this article from IBM. I simply made a DEMO.

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

The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?php

//chat.php

header(&#39;cache-control: private&#39;);

header(&#39;Content-Type: text/html; charset=utf-8&#39;);

?>

<html>

<script type="text/javascript">

function submitChat(obj) {

obj.submit();

document.getElementsByName(&#39;content&#39;)[0].value = &#39;&#39;;

}

</script>

<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)" />

</form>

</html>

Copy after login

The other one is to save the chat content submitted by the user. I simply write the text without any locking. This is just a simple version:

The code is as follows:

1

2

3

4

5

6

7

8

9

<?php

$content = trim($_POST[&#39;content&#39;]);

if $content) {

$fp = fopen(&#39;./chat.txt&#39;, &#39;a&#39;);

fwrite($fp, $content . "\n");

fclose($fp);

clearstatcache();

}

?>

Copy after login

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

The code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<?php

header(&#39;cache-control: private&#39;);

header(&#39;Content-Type: text/html; charset=utf-8&#39;);

//测试设置30秒超时,一般会设置比较长时间。

set_time_limit(30);

//这一行是为了搞定IE这个BT

echo str_repeat(&#39; &#39;, 256);

ob_flush();

flush();

$fp = new SplFileObject(&#39;./chat.txt&#39;, &#39;r+&#39;);

$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 &#39;<div>&#39;;

echo htmlspecialchars($content);

echo "</div>";

flush();

$fp->next();

$i++;

}

} else {

$fp->seek($i - 1);

$fp->next();

}

{

//这里可以添加心跳检测后退出循环

}

usleep(1000);

}

?>

Copy after login

I will explain it line by line, which is actually easier to understand:

06. Set a timeout, because it requires Maintaining a long HTTP connection will definitely take a longer time, maybe a few hours. The article mentioned above 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, maybe Other browsers 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 file lines so that the content can be read from the end of this line.

The following while loop is an infinite loop, which outputs the file content in a loop. Each time it determines whether the end of the file has been reached. 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 move the pointer forward one line and continue to loop, 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 You may also need to do some heartbeat recording 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, the endless loop is launched and the HTTP connection is closed.


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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
What does http status code 520 mean? What does http status code 520 mean? Oct 13, 2023 pm 03:11 PM

HTTP status code 520 means that the server encountered an unknown error while processing the request and cannot provide more specific information. Used to indicate that an unknown error occurred when the server was processing the request, which may be caused by server configuration problems, network problems, or other unknown reasons. This is usually caused by server configuration issues, network issues, server overload, or coding errors. If you encounter a status code 520 error, it is best to contact the website administrator or technical support team for more information and assistance.

What is http status code 403? What is http status code 403? Oct 07, 2023 pm 02:04 PM

HTTP status code 403 means that the server rejected the client's request. The solution to http status code 403 is: 1. Check the authentication credentials. If the server requires authentication, ensure that the correct credentials are provided; 2. Check the IP address restrictions. If the server has restricted the IP address, ensure that the client's IP address is restricted. Whitelisted or not blacklisted; 3. Check the file permission settings. If the 403 status code is related to the permission settings of the file or directory, ensure that the client has sufficient permissions to access these files or directories, etc.

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

How to use Nginx Proxy Manager to implement automatic jump from HTTP to HTTPS How to use Nginx Proxy Manager to implement automatic jump from HTTP to HTTPS Sep 26, 2023 am 11:19 AM

How to use NginxProxyManager to implement automatic jump from HTTP to HTTPS. With the development of the Internet, more and more websites are beginning to use the HTTPS protocol to encrypt data transmission to improve data security and user privacy protection. Since the HTTPS protocol requires the support of an SSL certificate, certain technical support is required when deploying the HTTPS protocol. Nginx is a powerful and commonly used HTTP server and reverse proxy server, and NginxProxy

HTTP 200 OK: Understand the meaning and purpose of a successful response HTTP 200 OK: Understand the meaning and purpose of a successful response Dec 26, 2023 am 10:25 AM

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

Send POST request with form data using http.PostForm function Send POST request with form data using http.PostForm function Jul 25, 2023 pm 10:51 PM

Use the http.PostForm function to send a POST request with form data. In the http package of the Go language, you can use the http.PostForm function to send a POST request with form data. The prototype of the http.PostForm function is as follows: funcPostForm(urlstring,dataurl.Values)(resp*http.Response,errerror)where, u

Quick Application: Practical Development Case Analysis of PHP Asynchronous HTTP Download of Multiple Files Quick Application: Practical Development Case Analysis of PHP Asynchronous HTTP Download of Multiple Files Sep 12, 2023 pm 01:15 PM

Quick Application: Practical Development Case Analysis of PHP Asynchronous HTTP Download of Multiple Files With the development of the Internet, the file download function has become one of the basic needs of many websites and applications. For scenarios where multiple files need to be downloaded at the same time, the traditional synchronous download method is often inefficient and time-consuming. For this reason, using PHP to download multiple files asynchronously over HTTP has become an increasingly common solution. This article will analyze in detail how to use PHP asynchronous HTTP through an actual development case.

http request 415 error solution http request 415 error solution Nov 14, 2023 am 10:49 AM

Solution: 1. Check the Content-Type in the request header; 2. Check the data format in the request body; 3. Use the appropriate encoding format; 4. Use the appropriate request method; 5. Check the server-side support.

See all articles