When I recently used Ratchet (a PHP websocket framework) to transform a PHP website, an error occurred:
"It is set to 1024, but you have descriptors numbered at least as high as 1266.
--enable-fd-setsize=2048 is recommended, but you may want to set it
to equal the maximum number of open files supported by your system"
After several twists and turns, I found that the reason is that the PHP source code sets FD_SIZE to 1024. Once there are more than 1024 websocket connections, this error will be reported. The solution on the Internet is basically to modify the PHP source code and recompile PHP. However, I personally think that modifying the PHP source code is risky, so I came up with a new idea and successfully used it in the project (you are welcome to submit a copy).
The basic principle is to open several more websocket service processes in the background, and each process uses a different port number. The front-end js randomly connects to the websocket service process port number open in the background. In this way, each websocket service process has 1024 available connections. The number of websocket service processes required can be calculated based on the peak number of connections of the website. Of course, some margin needs to be left. In this way, there is no need to recompile the PHP source code, and it can easily break through the 1024 connection limit of PHP websocket.
Backend implementation
Write a push-server.php as a websocket service. The implementation of push-server can refer to the Ratchet example, but it needs a slight modification, that is, you can enter port as the command line parameter.
$port = $argv[1]; if ($port == ""){ $port = 40003; // 默认端口,如果启动push-server.php时不写参数,则使用40003端口 } // .....省略其他代码 ..... // 将$port作为监听端口传入 $webSock->listen($port, '0.0.0.0');
As needed, multiple websocket processes can be started, such as:
php push-server 40003
php push-server 40004
php push-server 40005
In this way, the background can tolerate 1024 * 3 = 3072 websocket connections.
Front-end implementation
The code to randomly obtain the connection service is as follows:
<span function</span><span getWSServer() { </span><span var</span> serverPorts = ['40003', '40004', '40005'<span ]; </span><span var</span> server = 'ws://youhost'<span ; </span><span var</span> randomPortIndex = Math.floor(Math.random() *<span serverPorts.length); server </span>+= ':' +<span serverPorts[randomPortIndex]; </span><span return</span><span server; };</span>
Of course, you can also specify when to connect to a certain websocket service according to your own needs, so I won’t go into details.