您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
workerman端口复用reusePort属性实现同一个入口监听多个协议及端口
发布时间:2021-11-29 23:00:21编辑:雪饮阅读()
这个就很有意思了像是下面这样,同一个入口文件,既能处理text协议,也能处理http协议:
start.php:
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('text://0.0.0.0:2015');
$worker->count = 4;
// 每个进程启动后在当前进程新增一个监听
$worker->onWorkerStart = function($worker)
{
$inner_worker = new Worker('http://0.0.0.0:2016');
/**
* 多个进程监听同一个端口(监听套接字不是继承自父进程)
* 需要开启端口复用,不然会报Address already in use错误
*/
$inner_worker->reusePort = true;
$inner_worker->onMessage = 'on_message';
// 执行监听
$inner_worker->listen();
};
$worker->onMessage = 'on_message';
function on_message(TcpConnection $connection, $data)
{
$connection->send("hello\n");
}
// 运行worker
Worker::runAll();
服务端运行:
[root@localhost workerman]# php -c /usr/local/php734/lib/php/php.ini start.php start
Workerman[start.php] start in DEBUG mode
----------------------------------------- WORKERMAN -----------------------------------------
Workerman version:4.0.22 PHP version:7.3.4
------------------------------------------ WORKERS ------------------------------------------
proto user worker listen processes status
tcp root none text://0.0.0.0:2015 4 [OK]
---------------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.
text协议的客户端运行:
[root@localhost workerman]# telnet 127.0.0.1 2015
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hai
hello
http协议的客户端运行:
[root@localhost workerman]# elinks 127.0.0.1:2016 -dump
hello
关键字词:workerman,reusePort,单入口,多监听,多个协议,端口,多协议