Workerman\Connection\AsyncTcpConnection::connect PHP Method

connect() public method

Do connect.
public connect ( ) : void
return void
    public function connect()
    {
        if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING && $this->_status !== self::STATUS_CLOSED) {
            return;
        }
        $this->_status = self::STATUS_CONNECTING;
        $this->_connectStartTime = microtime(true);
        // Open socket connection asynchronously.
        if ($this->_contextOption) {
            $context = stream_context_create($this->_contextOption);
            $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT, $context);
        } else {
            $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT);
        }
        // If failed attempt to emit onError callback.
        if (!$this->_socket) {
            $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr);
            if ($this->_status === self::STATUS_CLOSING) {
                $this->destroy();
            }
            if ($this->_status === self::STATUS_CLOSED) {
                $this->onConnect = null;
            }
            return;
        }
        // Add socket to global event loop waiting connection is successfully established or faild.
        Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
    }

Usage Example

Beispiel #1
0
            // 当客户端发来数据时,加密数据,并发给远程服务端
            $connection->onMessage = function ($connection, $data) {
                $connection->opposite->send($connection->encryptor->encrypt($data));
            };
            // 当客户端关闭连接时,关闭远程服务端的连接
            $connection->onClose = function ($connection) {
                $connection->opposite->close();
                $connection->opposite = null;
            };
            // 当客户端连接上有错误时,关闭远程服务端连接
            $connection->onError = function ($connection, $code, $msg) {
                echo "connection err code:{$code} msg:{$msg}\n";
                $connection->close();
                if (isset($connection->opposite)) {
                    $connection->opposite->close();
                }
            };
            // 执行远程连接
            $remote_connection->connect();
            // 改变当前连接的状态为STAGE_STREAM,即开始转发数据流
            $connection->state = STAGE_STREAM;
            //转发首个数据包,包含由客户端封装的目标地址,端口号等信息
            $buffer = substr($buffer, 3);
            $buffer = $connection->encryptor->encrypt($buffer);
            $remote_connection->send($buffer);
    }
};
// 如果不是在根目录启动,则运行runAll方法
if (!defined('GLOBAL_START')) {
    Worker::runAll();
}
All Usage Examples Of Workerman\Connection\AsyncTcpConnection::connect