Summary of common problems with PHP Swoole long connections
Connection failure problem
Example
Among them, Redis is common The error report is:
Configuration item: timeout
Error message: Error while reading line from the server
Redis can Configure if the client does not send data to the Redis server after a certain number of seconds, the connection will be closed.
Recommended learning: swoole tutorial
MySQL common errors:
Configuration items: wait_timeout & interactive_timeout
Error message: has gone away
Like the Redis server, MySQL will also clean up useless connections regularly.
How to solve
1. Reconnect when using
2. Send heartbeats regularly to maintain the connection
When using Reconnecting
The advantage is that it is simple, but the disadvantage is that it faces the problem of short connections.
Send heartbeat regularly to maintain connection
Recommended.
How to maintain a long connection
tcp_keepalive implemented in the tcp protocol
The bottom layer of the operating system provides a set of tcpkeepalive
Configuration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
The bottom layer of Swoole has opened up these configurations, for example:
1 2 3 4 5 6 7 8 9 10 11 |
|
Among them:
1 2 3 4 5 |
|
Let’s Let’s experience the actual test. The server script 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 |
|
Let’s start this server:
1 |
|
Then capture the packet through tcpdump:
~/codeDir/phpCode /hyperf-skeleton # tcpdump -i lo port 6666
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on lo, link-type EN10MB (Ethernet) , capture size 262144 bytes
We are listening for data packets on port 6666 on lo at this time.
Then we use the client to connect to it:
1 |
|
At this time, the server will print out the message:
1 2 |
|
The output information of tcpdump is as follows:
1 2 3 4 5 6 7 8 9 |
|
We will find that at the beginning, the three-way handshake packet will be printed:
1 2 3 |
|
Then, it will stay for 4s without any packet output.
After that, a group will be printed out every 1 second or so:
1 2 |
|
In fact, this is the strategy we configured:
1 2 |
|
Because the bottom layer of our operating system will automatically The client responds with ack, so the connection will not be closed after 5 probes. The bottom layer of the operating system will continuously send a group of packets like this:
1 2 |
|
If we want to close the connection after testing 5 times, we can disable the packets on port 6666:
1 |
|
This will Disable all packets coming from port 6666. Naturally, the server will not be able to receive ack packets sent from the client.
Then the server will print out close after 5 seconds (the server actively calls the close method and sends a FIN packet to the client):
1 2 3 |
|
Let’s restore the iptables rules:
1 |
|
That is, the rules we set are deleted.
The heartbeat function is implemented through tcp_keepalive. The advantage is that it is simple. You can complete this function without writing code, and the heartbeat packet sent is small. The disadvantage is that it depends on the network environment of the system. It must be ensured that both the server and the client implement such functions, and the client needs to cooperate in sending heartbeat packets.
Another more serious shortcoming is that if the client and the server are not directly connected, but are connected through a proxy, such as the socks5 proxy, it will only forward application layer packets and not forward them. For lower-level TCP detection packets, the heartbeat function will be invalid.
So, Swoole provides other solutions, a set of configurations for detecting dead connections.
1 2 |
|
heartbeat implemented by swoole
Let’s test it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Then start the server:
~/codeDir/phpCode/hyperf- skeleton # php server.php
Then start tcpdump:
1 2 3 |
|
Then start the client:
~/codeDir/phpCode/hyperf-skeleton # nc 127.0.0.1 6666
At this time, the server prints:
1 2 |
|
Then tcpdump prints:
1 2 3 |
|
This is the three-way handshake information.
Then after 5 seconds, tcpdump will print out:
02:48:36.985027 IP localhost.6666 > localhost.42123: Flags [F.], seq 1, ack 1, win 342, options [nop,nop,TS val 10193789 ecr 10193342], length 0
02:48:36.992172 IP localhost.42123 > localhost.6666: Flags [.], ack 2, win 342, options [nop,nop,TS val 10193790 ecr 10193789], length 0
That is, the server sent a FIN packet. Because the client sent no data, Swoole closed the connection.
Then the server will print:
1 2 3 |
|
So, there are certain differences between heartbeat and tcp keepalive. Tcp keepalive has the function of keeping the connection alive, but heartbeat saves It simply detects a connection without data and then closes it. It can only be configured on the server side. If it needs to be kept alive, the client can also cooperate to send heartbeats.
如果我们不想让服务端close掉连接,那么就得在应用层里面不断的发送数据包来进行保活,例如我在nc客户端里面不断的发送包:
1 2 3 4 5 6 7 8 9 10 |
|
我发送了9个ping包给服务器,tcpdump的输出如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
有9组数据包的发送。(这里的Flags [P.]代表Push的含义)
此时服务器还没有close掉连接,实现了客户端保活连接的功能。然后我们停止发送ping,过了5秒后tcpdump就会输出一组:
02:58:14.811761 IP localhost.6666 > localhost.44195: Flags [F.], seq 1, ack 46, win 342, options [nop,nop,TS val 10251636 ecr 10251145], length 0
02:58:14.816420 IP localhost.44195 > localhost.6666: Flags [.], ack 2, win 342, options [nop,nop,TS val 10251637 ecr 10251636], length 0
服务端那边发送了FIN包,说明服务端close掉了连接。服务端的输出如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
然后我们在客户端那边ctrl + c来关闭连接:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
此时,tcpdump的输出如下:
1 2 |
|
应用层心跳
1、制定ping/pong协议(mysql等自带ping协议)
2、客户端灵活的发送ping心跳包
3、服务端OnRecive检查可用性回复pong
例如:
1 2 3 4 5 6 7 8 9 10 |
|
结论
1、tcp的keepalive最简单,但是有兼容性问题,不够灵活
2、swoole提供的keepalive最实用,但是需要客户端配合,复杂度适中
3、应用层的keepalive最灵活但是最麻烦
The above is the detailed content of Summary of common problems with PHP Swoole long connections. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
