通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
## 1 目录结构 ~~~ Workerman/ ;Workerman内核代码 Connection/ ;socket连接 ConnectionInterface.php ;socket连接接口 TcpConnecttion.php ;Tcp连接 AsyncTcpConnecttion.php ;异步Tcp连接 UdpConnection.php ;Udp连接 Events/ ;网络事件库 EventInterface.php ;网络事件库接口 Libevent.php ;Libevent网络事件库 Ev.php ;LivEv网络事件库 Select.php ;Select网络事件库 Lib/ ;类库 Constants.php ;常量定义 Timer.php ;定时器 Protocols/ ProtocolInterface.php ;协议接口 Http mime.types ;mime类型 Http.php ;http协议 Text.php ;Text协议 Frame.php ;Frame协议 Websocket.php ;websocket协议 Worker.php ;Worker WebServer.php ;WebServer Autoloader.php ;自动加载器 ~~~ ## 2 主体流程 ~~~ <?php use Workerman\Worker; require_once '/your/path/Workerman/Autoloader.php'; $global_uid = 0; // 当客户端连上来时分配uid,并保存连接,并通知所有客户端 function handle_connection($connection) { global $text_worker, $global_uid; // 为这个链接分配一个uid $connection->uid = ++$global_uid; } // 当客户端发送消息过来时,转发给所有人 function handle_message($connection, $data) { global $text_worker; foreach($text_worker->connections as $conn) { $conn->send("user[{$connection->uid}] said: $data"); } } // 当客户端断开时,广播给所有客户端 function handle_close($connection) { global $text_worker; foreach($text_worker->connections as $conn) { $conn->send("user[{$connection->uid}] logout"); } } // 创建一个文本协议的Worker监听2347接口 $text_worker = new Worker("text://0.0.0.0:2347"); // 只启动1个进程,这样方便客户端之间传输数据 $text_worker->count = 1; $text_worker->onConnect = 'handle_connection'; $text_worker->onMessage = 'handle_message'; $text_worker->onClose = 'handle_close'; Worker::runAll(); ~~~ >[info] 1 创建worker处理对象 `$text_worker = new Worker("text://0.0.0.0:2347");` >[info] 2 设置启动进程数目 `$text_worker->count = 1;` >[info] 3 注册事件接口 ~~~ $text_worker->onConnect = 'handle_connection'; $text_worker->onMessage = 'handle_message'; $text_worker->onClose = 'handle_close'; ~~~ >[info] 4 启动worker `Worker::runAll();`