当前位置: 首页>>代码示例>>PHP>>正文


PHP Workerman\Worker类代码示例

本文整理汇总了PHP中Workerman\Worker的典型用法代码示例。如果您正苦于以下问题:PHP Worker类的具体用法?PHP Worker怎么用?PHP Worker使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Worker类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: startAction

 public function startAction()
 {
     $worker = new Worker('tcp://0.0.0.0:1234');
     $worker->count = 2;
     $worker->onMessage = array($this, 'onMessage');
     $worker->onConnect = array($this, 'onConnect');
     $worker->onWorkerStart = array($this, 'onWorkerStart');
     $worker->runAll();
 }
开发者ID:jixm,项目名称:Simple-PHP-MVC-Skeleton,代码行数:9,代码来源:Walkman.php

示例2: onWorkerStart

 /**
  * 当Gateway启动的时候触发的回调函数
  * @return void
  */
 public function onWorkerStart()
 {
     // 分配一个内部通讯端口
     $this->lanPort = $this->startPort - posix_getppid() + posix_getpid();
     if ($this->lanPort < 0 || $this->lanPort >= 65535) {
         $this->lanPort = rand($this->startPort, 65535);
     }
     // 如果有设置心跳,则定时执行
     if ($this->pingInterval > 0) {
         Timer::add($this->pingInterval, array($this, 'ping'));
     }
     // 初始化gateway内部的监听,用于监听worker的连接已经连接上发来的数据
     $this->_innerTcpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
     $this->_innerTcpWorker->listen();
     $this->_innerUdpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
     $this->_innerUdpWorker->transport = 'udp';
     $this->_innerUdpWorker->listen();
     // 重新设置自动加载根目录
     Autoloader::setRootPath($this->_appInitPath);
     // 设置内部监听的相关回调
     $this->_innerTcpWorker->onMessage = array($this, 'onWorkerMessage');
     $this->_innerUdpWorker->onMessage = array($this, 'onWorkerMessage');
     $this->_innerTcpWorker->onConnect = array($this, 'onWorkerConnect');
     $this->_innerTcpWorker->onClose = array($this, 'onWorkerClose');
     // 注册gateway的内部通讯地址,worker去连这个地址,以便gateway与worker之间建立起TCP长连接
     if (!$this->registerAddress()) {
         $this->log('registerAddress fail and exit');
         Worker::stopAll();
     }
     if ($this->_onWorkerStart) {
         call_user_func($this->_onWorkerStart, $this);
     }
 }
开发者ID:highestgoodlikewater,项目名称:Workerman-ThinkPHP-Redis,代码行数:37,代码来源:Gateway.php

示例3: __construct

 public function __construct($socket_name)
 {
     parent::__construct($socket_name);
     $this->onWorkerStart = array($this, 'onStart');
     $this->onMessage = array($this, 'onMessage');
     $this->onWorkerStop = array($this, 'onStop');
 }
开发者ID:nooner2014,项目名称:workerman-statistics,代码行数:7,代码来源:StatisticWorker.php

示例4: run

 /**
  * Run webserver instance.
  *
  * @see Workerman.Worker::run()
  */
 public function run()
 {
     $this->_onWorkerStart = $this->onWorkerStart;
     $this->onWorkerStart = array($this, 'onWorkerStart');
     $this->onMessage = array($this, 'onMessage');
     parent::run();
 }
开发者ID:google2013,项目名称:Workerman,代码行数:12,代码来源:WebServer.php

示例5: fire

 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     //
     global $argv;
     $argv[0] = 'artisan';
     $argv[1] = 'reload';
     Worker::runAll();
 }
开发者ID:Hehe-Zhc,项目名称:workerboy,代码行数:13,代码来源:ReloadCommand.php

示例6: fire

 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     //
     $deamonMode = $this->option('deamon');
     global $argv;
     $argv[0] = 'artisan';
     $argv[1] = 'restart';
     $argv[2] = $deamonMode ? '-d' : null;
     Worker::runAll();
 }
开发者ID:Hehe-Zhc,项目名称:workerboy,代码行数:15,代码来源:RestartCommand.php

示例7: handle

 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $ws_worker = new Worker("websocket://0.0.0.0:2346");
     $ws_worker->onConnect = function ($connection) {
         echo "New connection\n";
     };
     $ws_worker->onMessage = function (TcpConnection $connection, $data) {
         // 转发数据给所有客户端
         foreach ($connection->worker->connections as $connection) {
             /** @var TcpConnection $connection */
             $connection->send($data);
         }
     };
     $ws_worker->onClose = function ($connection) {
         echo "Connection closed\n";
     };
     // Hack Run worker
     global $argv;
     $argv = [null, 'start'];
     $ws_worker->runAll();
 }
开发者ID:shellus,项目名称:laravel_worker,代码行数:26,代码来源:WsServerStart.php

示例8: run

 /**
  * 运行
  * @see Workerman.Worker::run()
  */
 public function run()
 {
     echo 123;
     $htmlStr = file_get_contents('http://www.baidu.com');
     for ($i = 0; $i < 200; $i++) {
         if ($this->count < 200) {
             file_put_contents('/www/html/workerman/html/chat1/test.log', $this->count++ . "\r\n", FILE_APPEND);
             sleep(3);
         }
     }
     echo 456;
     parent::run();
 }
开发者ID:suhanyujie,项目名称:digitalOceanVps,代码行数:17,代码来源:MyWorker.php

示例9: start

 /**
  * 启动服务器
  * @return void
  */
 public function start()
 {
     if ($this->isStart) {
         return;
     }
     $this->isStart = true;
     Worker::runAll();
 }
开发者ID:yb199478,项目名称:framework,代码行数:12,代码来源:WorkermanServer.php

示例10: Worker

 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
use Workerman\Worker;
use Workerman\WebServer;
use Workerman\Protocols\Websocket;
// 自动加载类
require_once __DIR__ . '/../../Workerman/Autoloader.php';
$recv_worker = new Worker('Websocket://0.0.0.0:8080');
$recv_worker->onWorkerStart = function ($recv_worker) {
    $send_worker = new Worker('Websocket://0.0.0.0:8008');
    $send_worker->onMessage = function ($connection, $data) {
    };
    $recv_worker->sendWorker = $send_worker;
    $send_worker->listen();
};
$recv_worker->onMessage = function ($connection, $data) use($recv_worker) {
    foreach ($recv_worker->sendWorker->connections as $send_connection) {
        //$send_connection->websocketType = "\x82";
        $send_connection->send($data);
    }
};
// WebServer
$web = new WebServer("http://0.0.0.0:8088");
// WebServer数量
$web->count = 2;
开发者ID:ufoe,项目名称:live-camera,代码行数:31,代码来源:start.php

示例11: function

    // On disconnect
    $socket->on('disconnect', function () use($socket) {
        if (!isset($socket->uid)) {
            return;
        }
        global $uidConnectionMap, $senderIO;
        // No users online
        if (--$uidConnectionMap[$socket->uid] <= 0) {
            unset($uidConnectionMap[$socket->uid]);
        }
    });
});
// New http service to send data to user
$senderIO->on('workerStart', function () {
    // Listening to a port
    $innerHttpWorker = new Worker('http://0.0.0.0:' . SERVER_API_PORT);
    // On msg receiving
    $innerHttpWorker->onMessage = function ($httpConnection, $data) {
        if (!isset($_REQUEST) && count($_REQUEST) <= 0) {
            return $httpConnection->send(json_encode(array("result" => false)));
        }
        // Send msg url like: "type=sendTextMsg&sendTo=xxxx&sendContent=xxxx"
        switch ($_REQUEST['type']) {
            case 'sendTextMsg':
                global $senderIO;
                if (isset($_REQUEST['sendTo']) && !empty($_REQUEST['sendTo'])) {
                    $SendTo = $_REQUEST['sendTo'];
                }
                $SendContent = json_encode(array("data" => htmlspecialchars($_REQUEST['sendContent'])));
                if (!empty($SendTo)) {
                    $senderIO->to($SendTo)->emit('new_msg_receive', $SendContent);
开发者ID:qiushuiqs,项目名称:RocketPush,代码行数:31,代码来源:start.php

示例12: forkOneWorker

 /**
  * Fork one worker process.
  * @param Worker $worker
  * @throws Exception
  */
 protected static function forkOneWorker($worker)
 {
     $pid = pcntl_fork();
     // Get available worker id.
     $id = self::getId($worker->workerId, 0);
     // For master process.
     if ($pid > 0) {
         self::$_pidMap[$worker->workerId][$pid] = $pid;
         self::$_idMap[$worker->workerId][$id] = $pid;
     } elseif (0 === $pid) {
         if ($worker->reusePort) {
             $worker->listen();
         }
         if (self::$_status === self::STATUS_STARTING) {
             self::resetStd();
         }
         self::$_pidMap = array();
         self::$_workers = array($worker->workerId => $worker);
         Timer::delAll();
         self::setProcessTitle('WorkerMan: worker process  ' . $worker->name . ' ' . $worker->getSocketName());
         $worker->setUserAndGroup();
         $worker->id = $id;
         $worker->run();
         exit(250);
     } else {
         throw new Exception("forkOneWorker fail");
     }
 }
开发者ID:TongJiankang,项目名称:Workerman,代码行数:33,代码来源:Worker.php

示例13: destroy

 /**
  * Destroy connection.
  *
  * @return void
  */
 public function destroy()
 {
     // Avoid repeated calls.
     if ($this->_status === self::STATUS_CLOSED) {
         return;
     }
     // Remove event listener.
     Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
     Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
     // Close socket.
     @fclose($this->_socket);
     // Remove from worker->connections.
     if ($this->worker) {
         unset($this->worker->connections[$this->_id]);
     }
     $this->_status = self::STATUS_CLOSED;
     // Try to emit onClose callback.
     if ($this->onClose) {
         try {
             call_user_func($this->onClose, $this);
         } catch (\Exception $e) {
             Worker::log($e);
             exit(250);
         } catch (\Error $e) {
             Worker::log($e);
             exit(250);
         }
     }
     // Try to emit protocol::onClose
     if (method_exists($this->protocol, 'onClose')) {
         try {
             call_user_func(array($this->protocol, 'onClose'), $this);
         } catch (\Exception $e) {
             Worker::log($e);
             exit(250);
         } catch (\Error $e) {
             Worker::log($e);
             exit(250);
         }
     }
     if ($this->_status === self::STATUS_CLOSED) {
         // Cleaning up the callback to avoid memory leaks.
         $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
     }
 }
开发者ID:amlun,项目名称:Workerman,代码行数:50,代码来源:TcpConnection.php

示例14: forkOneWorker

 /**
  * 创建一个子进程
  * @param Worker $worker
  * @throws Exception
  */
 protected static function forkOneWorker($worker)
 {
     $pid = pcntl_fork();
     // 主进程记录子进程pid
     if ($pid > 0) {
         self::$_pidMap[$worker->workerId][$pid] = $pid;
     } elseif (0 === $pid) {
         // 启动过程中尝试重定向标准输出
         if (self::$_status === self::STATUS_STARTING) {
             self::resetStd();
         }
         self::$_pidMap = array();
         self::$_workers = array($worker->workerId => $worker);
         Timer::delAll();
         self::setProcessTitle('WorkerMan: worker process  ' . $worker->name . ' ' . $worker->getSocketName());
         self::setProcessUser($worker->user);
         $worker->run();
         exit(250);
     } else {
         throw new Exception("forkOneWorker fail");
     }
 }
开发者ID:hongbo819,项目名称:webChat,代码行数:27,代码来源:Worker.php

示例15: dealHandshake

 /**
  * Websocket handshake.
  *
  * @param string                              $buffer
  * @param \Workerman\Connection\TcpConnection $connection
  * @return int
  */
 protected static function dealHandshake($buffer, $connection)
 {
     // HTTP protocol.
     if (0 === strpos($buffer, 'GET')) {
         // Find \r\n\r\n.
         $heder_end_pos = strpos($buffer, "\r\n\r\n");
         if (!$heder_end_pos) {
             return 0;
         }
         $header_length = $heder_end_pos + 4;
         // Get Sec-WebSocket-Key.
         $Sec_WebSocket_Key = '';
         if (preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
             $Sec_WebSocket_Key = $match[1];
         } else {
             $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Sec-WebSocket-Key not found.<br>This is a WebSocket service and can not be accessed via HTTP.", true);
             $connection->close();
             return 0;
         }
         // Calculation websocket key.
         $new_key = base64_encode(sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
         // Handshake response data.
         $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n";
         $handshake_message .= "Upgrade: websocket\r\n";
         $handshake_message .= "Sec-WebSocket-Version: 13\r\n";
         $handshake_message .= "Connection: Upgrade\r\n";
         $handshake_message .= "Server: workerman/" . Worker::VERSION . "\r\n";
         $handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n\r\n";
         // Mark handshake complete..
         $connection->websocketHandshake = true;
         // Websocket data buffer.
         $connection->websocketDataBuffer = '';
         // Current websocket frame length.
         $connection->websocketCurrentFrameLength = 0;
         // Current websocket frame data.
         $connection->websocketCurrentFrameBuffer = '';
         // Consume handshake data.
         $connection->consumeRecvBuffer($header_length);
         // Send handshake response.
         $connection->send($handshake_message, true);
         // There are data waiting to be sent.
         if (!empty($connection->tmpWebsocketData)) {
             $connection->send($connection->tmpWebsocketData, true);
             $connection->tmpWebsocketData = '';
         }
         // blob or arraybuffer
         if (empty($connection->websocketType)) {
             $connection->websocketType = self::BINARY_TYPE_BLOB;
         }
         // Try to emit onWebSocketConnect callback.
         if (isset($connection->onWebSocketConnect)) {
             self::parseHttpHeader($buffer);
             try {
                 call_user_func($connection->onWebSocketConnect, $connection, $buffer);
             } catch (\Exception $e) {
                 Worker::log($e);
                 exit(250);
             } catch (\Error $e) {
                 Worker::log($e);
                 exit(250);
             }
             if (!empty($_SESSION) && class_exists('\\GatewayWorker\\Lib\\Context')) {
                 $connection->session = \GatewayWorker\Lib\Context::sessionEncode($_SESSION);
             }
             $_GET = $_SERVER = $_SESSION = $_COOKIE = array();
         }
         if (strlen($buffer) > $header_length) {
             return self::input(substr($buffer, $header_length), $connection);
         }
         return 0;
     } elseif (0 === strpos($buffer, '<polic')) {
         $policy_xml = '<?xml version="1.0"?><cross-domain-policy><site-control permitted-cross-domain-policies="all"/><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>' . "";
         $connection->send($policy_xml, true);
         $connection->consumeRecvBuffer(strlen($buffer));
         return 0;
     }
     // Bad websocket handshake request.
     $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ", true);
     $connection->close();
     return 0;
 }
开发者ID:amlun,项目名称:Workerman,代码行数:88,代码来源:Websocket.php


注:本文中的Workerman\Worker类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。