Exemple #1
3
 public function listen()
 {
     echo "Starting server at http://{$this->address}:{$this->port}...\n";
     $this->socket = stream_socket_server($this->address . ':' . $this->port, $errNo, $errStr);
     if (!$this->socket) {
         throw new Exception("Can't connect socket: [{$errNo}] {$errStr}");
     }
     $this->connections[] = $this->socket;
     while (1) {
         echo "connections:";
         var_dump($this->connections);
         $reads = $this->connections;
         $writes = NULL;
         $excepts = NULL;
         $modified = stream_select($reads, $writes, $excepts, 5);
         if ($modified === false) {
             break;
         }
         echo "modified fd:";
         var_dump($modified);
         echo "reads:";
         var_dump($reads);
         foreach ($reads as $modifiedRead) {
             if ($modifiedRead === $this->socket) {
                 $conn = stream_socket_accept($this->socket);
                 fwrite($conn, "Hello! The time is " . date("n/j/Y g:i a") . "\n");
                 $this->connections[] = $conn;
             } else {
                 $data = fread($modifiedRead, 1024);
                 var_dump($data);
                 if (strlen($data) === 0) {
                     // connection closed
                     $idx = array_search($modifiedRead, $this->connections, TRUE);
                     fclose($modifiedRead);
                     if ($idx != -1) {
                         unset($this->connections[$idx]);
                     }
                 } else {
                     if ($data === FALSE) {
                         echo "Something bad happened";
                         $idx = array_search($modifiedRead, $this->connections, TRUE);
                         if ($idx != -1) {
                             unset($this->connections[$idx]);
                         }
                     } else {
                         echo "The client has sent :";
                         var_dump($data);
                         fwrite($modifiedRead, "You have sent :[" . $data . "]\n");
                         fclose($modifiedRead);
                         $idx = array_search($modifiedRead, $this->connections, TRUE);
                         if ($idx != -1) {
                             unset($this->connections[$idx]);
                         }
                     }
                 }
             }
         }
     }
 }
Exemple #2
2
 /**
  * Runs the server.
  * This function will block forever and never return, except if an exception is thrown during the startup of the server.
  */
 public function run()
 {
     if (ini_get('max_execution_time') != 0) {
         throw new \LogicException('PHP must have no max_execution_time in order to start a server');
     }
     if (($this->socket = stream_socket_server($this->bindAddress, $errNo, $errString)) === false) {
         throw new \RuntimeException('Could not create listening socket: ' . $errString);
     }
     do {
         $readableSockets = [$this->socket];
         $write = null;
         $except = null;
         stream_select($readableSockets, $write, $except, 5);
         foreach ($readableSockets as $socket) {
             if ($socket === $this->socket) {
                 $newSocket = stream_socket_accept($this->socket);
                 try {
                     $request = new HTTPRequestFromStream($newSocket);
                     $response = new HTTPResponseToStream($newSocket);
                     $response->setHeader('Server', 'Niysu IPC server');
                     $response->setHeader('Connection', 'close');
                     $this->niysuServer->handle($request, $response);
                     stream_socket_shutdown($newSocket, STREAM_SHUT_RDWR);
                 } catch (\Exception $e) {
                     fwrite($newSocket, 'HTTP/1.1 500 Internal Server Error' . "\r\n");
                     fwrite($newSocket, 'Server: Niysu IPC server' . "\r\n\r\n");
                     fflush($newSocket);
                     stream_socket_shutdown($newSocket, STREAM_SHUT_RDWR);
                 }
             }
         }
     } while (true);
     stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
 }
 public static function setUpBeforeClass()
 {
     //Start the server
     $hostname = strpos(LOCAL_HOSTNAME, ':') !== false ? '[' . LOCAL_HOSTNAME . ']' : LOCAL_HOSTNAME;
     static::$server = stream_socket_server("tls://{$hostname}:" . LOCAL_PORT, static::$errorno, static::$errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, stream_context_create(array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'local_cert' => __DIR__ . DIRECTORY_SEPARATOR . CERTIFICATE_FILE . '.cer', 'cafile' => __DIR__ . DIRECTORY_SEPARATOR . CERTIFICATE_FILE . '.cer'))));
     return;
 }
Exemple #4
0
function ssl_server($port)
{
    $host = 'ssl://127.0.0.1' . ':' . $port;
    $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
    $data = "Sending bug48182\n";
    $pem = dirname(__FILE__) . '/bug46127.pem';
    $ssl_params = array('verify_peer' => false, 'allow_self_signed' => true, 'local_cert' => $pem);
    $ssl = array('ssl' => $ssl_params);
    $context = stream_context_create($ssl);
    $sock = stream_socket_server($host, $errno, $errstr, $flags, $context);
    if (!$sock) {
        return false;
    }
    $link = stream_socket_accept($sock);
    if (!$link) {
        return false;
    }
    // bad link?
    $r = array($link);
    $w = array();
    $e = array();
    if (stream_select($r, $w, $e, 1, 0) != 0) {
        $data .= fread($link, 8192);
    }
    $r = array();
    $w = array($link);
    if (stream_select($r, $w, $e, 1, 0) != 0) {
        $wrote = fwrite($link, $data, strlen($data));
    }
    // close stuff
    fclose($link);
    fclose($sock);
    exit;
}
Exemple #5
0
 public function run($force = false)
 {
     if ($force) {
         $this->killProgramsOnDreddPort();
     }
     $socket = sprintf('tcp://%s:%s', $this->host, $this->port);
     $server = stream_socket_server($socket, $errno, $errorMessage);
     if ($server === false) {
         throw new UnexpectedValueException("Server could not bind to socket: {$errorMessage}");
     }
     $buffer = "";
     for (;;) {
         $client = stream_socket_accept($server);
         while ($socketData = stream_socket_recvfrom($client, self::RECV_LENGTH)) {
             $buffer .= $socketData;
             // determine if message terminating character is present.
             if (strpos($buffer, self::MESSAGE_END) === false) {
                 continue;
             }
             $messages = [];
             foreach (explode(self::MESSAGE_END, $buffer) as $data) {
                 $message = json_decode($data);
                 // if not valid json the partial message needs saved
                 if (!$message) {
                     $buffer = $message;
                     continue;
                 }
                 $messages[] = $message;
             }
             foreach ($messages as $message) {
                 $this->processMessage($message, $client);
             }
         }
     }
 }
Exemple #6
0
 public function getLine($timeout)
 {
     if (!is_resource($this->server)) {
         $this->server = stream_socket_server('tcp://127.0.0.1:' . $this->port, $errno, $errstr);
         if (!is_resource($this->server)) {
             ezcLog::getInstance()->log(sprintf('Error opening socket: %d %s', $errno, $errstr), ezcLog::ERROR);
             return;
         }
     }
     if (!is_resource($this->client)) {
         ezcLog::getInstance()->log('waiting for client connect', ezcLog::DEBUG);
         $this->client = @stream_socket_accept($this->server, $timeout);
         if (is_resource($this->client)) {
             stream_set_blocking($this->client, 0);
             stream_set_timeout($this->client, $timeout);
         }
     }
     if (is_resource($this->client)) {
         ezcLog::getInstance()->log('reading input line from client', ezcLog::DEBUG);
         $line = trim(fgets($this->client));
         if ($line) {
             ezcLog::getInstance()->log('received input line ' . $line, ezcLog::DEBUG);
         } elseif (feof($this->client)) {
             ezcLog::getInstance()->log('client closed connection', ezcLog::INFO);
             $this->close();
         } else {
             //ezcLog::getInstance()->log( 'no client input, sleeping', ezcLog::INFO );
             sleep(1);
         }
         return $line;
     }
 }
 public function __construct($port)
 {
     global $errno, $errstr;
     if (!extension_loaded('libevent')) {
         die("Please install libevent extension firstly\n");
     }
     if ($port < 1024) {
         die("Port must be a number which bigger than 1024\n");
     }
     $socket_server = stream_socket_server("tcp://0.0.0.0:{$port}", $errno, $errstr);
     if (!$socket_server) {
         die("{$errstr} ({$errno})");
     }
     stream_set_blocking($socket_server, 0);
     // 非阻塞
     // event_base_new — Create and initialize new event base
     $base = event_base_new();
     // event_new — Create new event
     $event = event_new();
     // event_set — Prepare an event
     event_set($event, $socket_server, EV_READ | EV_PERSIST, [__CLASS__, 'ev_accept'], $base);
     // event_base_set — Associate event base with an event
     event_base_set($event, $base);
     // event_add — Add an event to the set of monitored events
     event_add($event);
     // event_base_loop — Handle events
     event_base_loop($base);
     self::$connections = [];
     self::$buffers = [];
 }
 public function onStart()
 {
     $listen = \Man\Core\Lib\Config::get($this->workerName . '.listen');
     $udp_address = str_replace('tcp', 'udp', $listen);
     $this->broadcastSocket = stream_socket_server($udp_address, $error_no, $error_msg, STREAM_SERVER_BIND);
     $this->event->add($this->broadcastSocket, \Man\Core\Events\BaseEvent::EV_READ, array($this, 'dealBroadcastUdp'));
 }
 /**
  * 进程启动
  */
 public function start()
 {
     // 安装信号处理函数
     $this->installSignal();
     // 添加accept事件
     $ret = $this->event->add($this->mainSocket, Man\Core\Events\BaseEvent::EV_READ, array($this, 'accept'));
     // 创建内部通信套接字
     $start_port = Man\Core\Lib\Config::get($this->workerName . '.lan_port_start');
     $this->lanPort = $start_port - posix_getppid() + posix_getpid();
     $this->lanIp = Man\Core\Lib\Config::get($this->workerName . '.lan_ip');
     if (!$this->lanIp) {
         $this->notice($this->workerName . '.lan_ip not set');
         $this->lanIp = '127.0.0.1';
     }
     $error_no = 0;
     $error_msg = '';
     $this->innerMainSocket = stream_socket_server("udp://" . $this->lanIp . ':' . $this->lanPort, $error_no, $error_msg, STREAM_SERVER_BIND);
     if (!$this->innerMainSocket) {
         $this->notice('create innerMainSocket fail and exit ' . $error_no . ':' . $error_msg);
         sleep(1);
         exit(0);
     } else {
         stream_set_blocking($this->innerMainSocket, 0);
     }
     $this->registerAddress("udp://" . $this->lanIp . ':' . $this->lanPort);
     // 添加读udp事件
     $this->event->add($this->innerMainSocket, Man\Core\Events\BaseEvent::EV_READ, array($this, 'recvUdp'));
     // 初始化到worker的通信地址
     $this->initWorkerAddresses();
     // 主体循环,整个子进程会阻塞在这个函数上
     $ret = $this->event->loop();
     $this->notice('worker loop exit');
     exit(0);
 }
Exemple #10
0
 public function setUp()
 {
     $this->host = '127.0.0.1';
     $this->port = 2000;
     $this->socketServer = stream_socket_server($this->host . ':' . $this->port);
     $this->kettle = new Kettle(new Connection($this->host, $this->port, new DummyLoop()));
 }
 public function __construct($ip = '0.0.0.0', $port = 8000)
 {
     $this->socket = stream_socket_server(sprintf("tcp://%s:%d", $ip, $port), $errno, $errstr);
     if (!$this->socket) {
         throw new Exception("Failed to create socket server. {$errstr}", $errno);
     }
 }
 public function __construct($pUrl)
 {
     $this->socket = stream_socket_server($pUrl, $errno, $errstr, STREAM_SERVER_BIND);
     if (!$this->socket) {
         die("{$errstr} ({$errno})");
     }
 }
Exemple #13
0
 public function listen($port, $host = '127.0.0.1')
 {
     $localSocket = '';
     if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
         $localSocket = 'tcp://' . $host . ':' . $port;
     } elseif (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
         // enclose IPv6 addresses in square brackets before appending port
         $localSocket = 'tcp://[' . $host . ']:' . $port;
     } elseif (preg_match('#^unix://#', $host)) {
         $localSocket = $host;
     } else {
         throw new \UnexpectedValueException('"' . $host . '" does not match to a set of supported transports. ' . 'Supported transports are: IPv4, IPv6 and unix:// .', 1433253311);
     }
     $this->master = stream_socket_server($localSocket, $errno, $errstr);
     if (false === $this->master) {
         $message = "Could not bind to {$localSocket} . Error: [{$errno}] {$errstr}";
         throw new ConnectionException($message, $errno);
     }
     stream_set_blocking($this->master, 0);
     $this->loop->addReadStream($this->master, function ($master) {
         $newSocket = stream_socket_accept($master);
         if (false === $newSocket) {
             $this->emit('error', array(new \RuntimeException('Error accepting new connection')));
             return;
         }
         $this->handleConnection($newSocket);
     });
 }
 /**
  * {@inheritdoc}
  */
 public function create(string $host, int $port = null, array $options = []) : Server
 {
     $protocol = (string) ($options['protocol'] ?? (null === $port ? 'unix' : 'tcp'));
     $autoClose = (bool) ($options['auto_close'] ?? true);
     $queue = (int) ($options['backlog'] ?? (defined('SOMAXCONN') ? SOMAXCONN : self::DEFAULT_BACKLOG));
     $pem = (string) ($options['pem'] ?? '');
     $passphrase = $options['passphrase'] ?? '';
     $name = (string) ($options['name'] ?? '');
     $verify = (string) ($options['verify_peer'] ?? self::DEFAULT_VERIFY_PEER);
     $allowSelfSigned = (bool) ($options['allow_self_signed'] ?? self::DEFAULT_ALLOW_SELF_SIGNED);
     $verifyDepth = (int) ($options['verify_depth'] ?? self::DEFAULT_VERIFY_DEPTH);
     $context = [];
     $context['socket'] = ['bindto' => Socket\makeName($host, $port), 'backlog' => $queue, 'ipv6_v6only' => true, 'so_reuseaddr' => (bool) ($options['reuseaddr'] ?? false), 'so_reuseport' => (bool) ($options['reuseport'] ?? false)];
     if ('' !== $pem) {
         if (!file_exists($pem)) {
             throw new InvalidArgumentError('No file found at given PEM path.');
         }
         $context['ssl'] = ['verify_peer' => $verify, 'verify_peer_name' => $verify, 'allow_self_signed' => $allowSelfSigned, 'verify_depth' => $verifyDepth, 'local_cert' => $pem, 'disable_compression' => true, 'SNI_enabled' => true, 'SNI_server_name' => $name, 'peer_name' => $name];
         if ('' !== $passphrase) {
             $context['ssl']['passphrase'] = $passphrase;
         }
     }
     $context = stream_context_create($context);
     $uri = Socket\makeUri($protocol, $host, $port);
     // Error reporting suppressed since stream_socket_server() emits an E_WARNING on failure (checked below).
     $socket = @stream_socket_server($uri, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
     if (!$socket || $errno) {
         throw new FailureException(sprintf('Could not create server %s: Errno: %d; %s', $uri, $errno, $errstr));
     }
     return new BasicServer($socket, $autoClose);
 }
 public function listen($port, $host = '127.0.0.1', $streamContext = array())
 {
     if (isset($streamContext['ssl']) && PHP_VERSION_ID < 50600) {
         throw new \RuntimeException('Secure connections are not available before PHP 5.6.0');
     }
     if (strpos($host, ':') !== false) {
         // enclose IPv6 addresses in square brackets before appending port
         $host = '[' . $host . ']';
     }
     $this->master = @stream_socket_server("tcp://{$host}:{$port}", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, stream_context_create($streamContext));
     if (false === $this->master) {
         $message = "Could not bind to tcp://{$host}:{$port}: {$errstr}";
         throw new ConnectionException($message, $errno);
     }
     stream_set_blocking($this->master, 0);
     $that = $this;
     $this->loop->addReadStream($this->master, function ($master) use($that) {
         $newSocket = @stream_socket_accept($master);
         if (false === $newSocket) {
             $that->emit('error', array(new \RuntimeException('Error accepting new connection')));
             return;
         }
         $that->handleConnection($newSocket);
     });
 }
 public function run()
 {
     $count = 0;
     $socket = stream_socket_server($this->socketString, &$errno, &$errstr);
     if (!$socket) {
         throw new RuntimeException($errstr);
     }
     while (true) {
         while (count($this->children) < $this->maxConnections) {
             $count++;
             $pid = pcntl_fork();
             if ($pid == -1) {
                 throw new RuntimeException('Couldn\'t fork');
             } elseif ($pid == 0) {
                 $this->createChild($socket, $count);
                 exit;
             }
             $this->children[] = $pid;
         }
         while (pcntl_wait($status, WNOHANG or WUNTRACED) > 0) {
             usleep(500000);
         }
         while (list($key, $val) = each($this->children)) {
             if (!posix_kill($val, 0)) {
                 unset($this->children[$key]);
             }
         }
         $this->children = array_values($this->children);
         usleep(500000);
     }
 }
Exemple #17
0
 /**
  * creates a tcp socket if needed and accepts connection to read
  * @return resource
  */
 public function fetchMessage()
 {
     if ($this->socket === null) {
         $this->socket = stream_socket_server(static::buildFullAddress($this->address));
     }
     return @stream_socket_accept($this->socket);
 }
 public function start($count = 1)
 {
     $loop = Factory::create();
     $server = stream_socket_server($this->config->getConnectionString());
     if ($server === false) {
         throw new \RuntimeException("create socket server failed");
     }
     $blocking = stream_set_blocking($server, 0);
     if ($blocking === false) {
         throw new \RuntimeException("stream_set_blocking failed");
     }
     $loop->addReadStream($server, function ($server) use($loop) {
         $dispatcher = $this->config->getDispatcher();
         if ($dispatcher !== null && !$dispatcher->acquire($server, $loop)) {
             return;
         }
         $conn = stream_socket_accept($server);
         $dispatcher->release($server, $loop);
         $loop->addReadStream($conn, function ($conn) use($loop) {
             call_user_func(array($this->handler, 'handle'), $conn, $loop);
         });
     });
     $master = new Master($loop, $count);
     $master->start();
 }
 function EpollSocketServer($port)
 {
     global $errno, $errstr;
     if (!extension_loaded('libevent')) {
         die("Please install libevent extension firstly/n");
     }
     if ($port < 1024) {
         die("Port must be a number which bigger than 1024/n");
     }
     $socket_server = stream_socket_server("tcp://0.0.0.0:{$port}", $errno, $errstr);
     if (!$socket_server) {
         die("{$errstr} ({$errno})");
     }
     stream_set_blocking($socket_server, 0);
     // 非阻塞
     $base = event_base_new();
     $event = event_new();
     event_set($event, $socket_server, EV_READ | EV_PERSIST, array(__CLASS__, 'ev_accept'), $base);
     event_base_set($event, $base);
     event_add($event);
     event_base_loop($base);
     self::$connections = array();
     self::$buffers = array();
     self::$imei = array();
 }
 public function hook_to_server()
 {
     $this->server->hook_processor($this->server_hook_id, $this);
     $err = array();
     $master = stream_socket_server("tcp://{$this->address}:{$this->port}", $err['errno'], $err['errstr']);
     $this->server->hook_master($this->server_hook_id, $master);
 }
Exemple #21
0
 public function listen($port, $host = '127.0.0.1', $protocol = 'tcp')
 {
     if (strpos($host, ':') !== false) {
         // enclose IPv6 addresses in square brackets before appending port
         $host = '[' . $host . ']';
     }
     $opts = ['socket' => ['backlog' => 1024, 'so_reuseport' => 1]];
     $flags = $protocol == 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
     $context = stream_context_create($opts);
     $this->master = @stream_socket_server("{$protocol}://{$host}:{$port}", $errorCode, $errorMessage, $flags, $context);
     if (false === $this->master) {
         $message = "Could not bind to tcp://{$host}:{$port}: {$errorMessage}";
         throw new ConnectionException($message, $errorCode);
     }
     // Try to open keep alive for tcp and disable Nagle algorithm.
     if (function_exists('socket_import_stream') && $protocol == 'tcp') {
         $socket = socket_import_stream($this->master);
         @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
         @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
     }
     stream_set_blocking($this->master, 0);
     $this->loop->addReadStream($this->master, function ($master) {
         $newSocket = stream_socket_accept($master, 0, $remote_address);
         if (false === $newSocket) {
             $this->notifyError(new \RuntimeException('Error accepting new connection'));
             return;
         }
         $this->handleConnection($newSocket);
     });
     return $this;
 }
Exemple #22
0
 public function createReceiver($address)
 {
     if (!defined('MCAST_JOIN_GROUP')) {
         throw new BadMethodCallException('MCAST_JOIN_GROUP not defined (requires PHP 5.4+)');
     }
     if (!function_exists('socket_import_stream')) {
         throw new BadMethodCallException('Function socket_import_stream missing (requires ext-sockets and PHP 5.4+)');
     }
     $parts = parse_url('udp://' . $address);
     $stream = @stream_socket_server('udp://0.0.0.0:' . $parts['port'], $errno, $errstr, STREAM_SERVER_BIND);
     if ($stream === false) {
         throw new RuntimeException('Unable to create receiving socket: ' . $errstr, $errno);
     }
     $socket = socket_import_stream($stream);
     if ($stream === false) {
         throw new RuntimeException('Unable to access underlying socket resource');
     }
     // allow multiple processes to bind to the same address
     $ret = socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
     if ($ret === false) {
         throw new RuntimeException('Unable to enable SO_REUSEADDR');
     }
     // join multicast group and bind to port
     $ret = socket_set_option($socket, IPPROTO_IP, MCAST_JOIN_GROUP, array('group' => $parts['host'], 'interface' => 0));
     if ($ret === false) {
         throw new RuntimeException('Unable to join multicast group');
     }
     return new DatagramSocket($this->loop, $stream);
 }
Exemple #23
0
 /**
  * Constructor.
  *
  * @param TCHDB $hdb
  * @param string $host
  * @param int $port
  * @param array $options
  * @return void
  * @throws RuntimeException
  */
 public function __construct(TCHDB $hdb, $host = 'localhost', $port = 8080, array $options = array())
 {
     $this->hdb = $hdb;
     if (strpos($host, '::') !== false) {
         $local_host = sprintf('tcp://[%s]:%d', $host, $port);
     } else {
         $local_host = sprintf('tcp://%s:%d', $host, $port);
     }
     $this->sock = stream_socket_server($local_host, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
     if (!$this->sock) {
         throw new RuntimeException($errstr, $errno);
     }
     if (isset($options['timeoutSec'])) {
         $this->timeoutSec = (int) $options['timeoutSec'];
     }
     if (isset($options['timeoutUsec'])) {
         $this->timeoutUsec = (int) $options['timeoutUsec'];
     }
     if (isset($options['maxLength'])) {
         $this->maxLength = (int) $options['maxLength'];
     }
     if ($this->maxLength <= 0) {
         $this->maxLength = PHP_INT_MAX;
     }
 }
 /**
  * 让该worker实例开始服务
  *
  * @param bool $is_daemon 告诉 Worker 当前是否运行在 daemon 模式, 非 daemon 模式不拦截 signals
  * @return void
  */
 public function serve($is_daemon = true)
 {
     // 触发该worker进程onServe事件,该进程整个生命周期只触发一次
     if ($this->onServe()) {
         return;
     }
     // 安装信号处理函数
     if ($is_daemon === true) {
         $this->installSignal();
     }
     // 初始化事件轮询库
     $this->event = new $this->eventLoopName();
     // 添加accept事件
     $this->event->add($this->mainSocket, BaseEvent::EV_ACCEPT, array($this, 'accept'));
     // 添加管道可读事件
     $this->event->add($this->channel, BaseEvent::EV_READ, array($this, 'dealCmd'), null, 0, 0);
     // 监听一个udp端口,用来广播ip
     $error_no = 0;
     $error_msg = '';
     // 创建监听socket
     $this->udpBroadSocket = @stream_socket_server('udp://0.0.0.0:' . PHPServerConfig::get('workers.' . $this->serviceName . '.port'), $error_no, $error_msg, STREAM_SERVER_BIND);
     if ($this->udpBroadSocket) {
         $this->event->add($this->udpBroadSocket, BaseEvent::EV_ACCEPT, array($this, 'recvBroadcastUdp'));
     }
     // 主体循环
     $ret = $this->event->loop();
     $this->notice("evet->loop returned " . var_export($ret, true));
     exit(self::EXIT_UNEXPECT_CODE);
 }
 public function start()
 {
     $pid = @file_get_contents($this->config['pid']);
     if ($pid) {
         die("already started\r\n");
     }
     if (empty($this->config['websocket']) && empty($this->config['localsocket']) && empty($this->config['master'])) {
         die("error: config: !websocket && !localsocket && !master\r\n");
     }
     $server = $service = $master = null;
     if (!empty($this->config['websocket'])) {
         //открываем серверный сокет
         $server = stream_socket_server($this->config['websocket'], $errorNumber, $errorString);
         stream_set_blocking($server, 0);
         if (!$server) {
             die("error: stream_socket_server: {$errorString} ({$errorNumber})\r\n");
         }
     }
     if (!empty($this->config['localsocket'])) {
         //создаём сокет для обработки сообщений от скриптов
         $service = stream_socket_server($this->config['localsocket'], $errorNumber, $errorString);
         stream_set_blocking($service, 0);
         if (!$service) {
             die("error: stream_socket_server: {$errorString} ({$errorNumber})\r\n");
         }
     }
     if (!empty($this->config['master'])) {
         //создаём сокет для обработки сообщений от скриптов
         $master = stream_socket_client($this->config['master'], $errorNumber, $errorString);
         stream_set_blocking($master, 0);
         if (!$master) {
             die("error: stream_socket_client: {$errorString} ({$errorNumber})\r\n");
         }
     }
     if (!empty($this->config['eventDriver']) && $this->config['eventDriver'] == 'libevent') {
         require_once 'WebsocketGenericLibevent.php';
     } elseif (!empty($this->config['eventDriver']) && $this->config['eventDriver'] == 'event') {
         require_once 'WebsocketGenericEvent.php';
     }
     file_put_contents($this->config['pid'], posix_getpid());
     //list($pid, $master, $workers) = $this->spawnWorkers();//создаём дочерние процессы
     /*if ($pid) {//мастер
           file_put_contents($this->config['pid'], $pid);
           fclose($server);//мастер не будет обрабатывать входящие соединения на основном сокете
           $masterClass = $this->config['master']['class'];
           $master = new $masterClass ($service, $workers);//мастер будет обрабатывать сообщения от скриптов и пересылать их в воркеры
           if (!empty($this->config['master']['timer'])) {
               $master->timer = $this->config['worker']['timer'];
           }
           $master->start();
       } else {//воркер*/
     $workerClass = $this->config['class'];
     $worker = new $workerClass($server, $service, $master);
     if (!empty($this->config['timer'])) {
         $worker->timer = $this->config['timer'];
     }
     $worker->start();
     //}
 }
Exemple #26
0
/**
 * Listen for client connections on the specified server $address
 *
 * @param string $address
 * @return resource
 */
function listen($address)
{
    $flags = \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN;
    if (!($socket = @\stream_socket_server($address, $errno, $errstr, $flags))) {
        throw new SocketException(\sprintf("Failed binding socket on %s: [Err# %s] %s", $address, $errno, $errstr));
    }
    return $socket;
}
Exemple #27
0
 public function setUp()
 {
     $this->server = stream_socket_server('127.0.0.1:8888', $errno = null, $errstr = null);
     if (!$this->server) {
         throw new Exception("Could not start test server [{$errno}:{$errstr}]");
     }
     $this->stream = new MioStream(fsockopen('127.0.0.1', 8888, $errno = null, $errstr = null), '127.0.0.1:8888');
 }
Exemple #28
0
 /**
  * Starts to listen for SIP messages over UDP
  */
 function start_server()
 {
     $this->handle = stream_socket_server('udp://' . $this->interface . ':' . $this->port, $errno, $errstr, STREAM_SERVER_BIND);
     if (!$this->handle) {
         die("{$errstr} ({$errno})");
     }
     echo "sip_server ready for connections at " . $this->interface . ":" . $this->port . "\n";
 }
Exemple #29
0
 public function testApiGetRemoteAddress_ReturnsValidAddress()
 {
     $remote = $this->tempSocketRemoteAddress();
     $server = stream_socket_server($remote);
     $socket = $this->createSocketMock($remote);
     $address = str_replace('tcp://', '', $remote);
     $this->assertEquals($address, $socket->getRemoteAddress());
 }
Exemple #30
0
 public function setUp()
 {
     $this->host = '127.0.0.1';
     $this->port = 2000;
     $this->loop = Factory::create();
     $this->connection = new Connection($this->host, $this->port, $this->loop);
     $this->socketServer = stream_socket_server($this->host . ':' . $this->port);
 }