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


PHP stream_socket_server函数代码示例

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


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

示例1: run

 /**
  * 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);
 }
开发者ID:tomaka17,项目名称:niysu,代码行数:38,代码来源:IPCServer.php

示例2: listen

 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]);
                         }
                     }
                 }
             }
         }
     }
 }
开发者ID:phpsgi,项目名称:funk,代码行数:59,代码来源:StreamSocketServer.php

示例3: setUpBeforeClass

 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;
 }
开发者ID:pear2,项目名称:net_transmitter,代码行数:7,代码来源:ServerEncryptedTest.php

示例4: ssl_server

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;
}
开发者ID:clifton98,项目名称:hhvm,代码行数:34,代码来源:bug48182.php

示例5: run

 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);
             }
         }
     }
 }
开发者ID:ddelnano,项目名称:dredd-hooks-php,代码行数:35,代码来源:Server.php

示例6: getLine

 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;
     }
 }
开发者ID:jou,项目名称:ymc-components,代码行数:32,代码来源:simple_server.php

示例7: __construct

 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 = [];
 }
开发者ID:CraryPrimitiveMan,项目名称:code-examples,代码行数:30,代码来源:epoll_server.php

示例8: onStart

 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'));
 }
开发者ID:bennysuh,项目名称:myself-wokerman,代码行数:7,代码来源:StatisticProvider.php

示例9: start

 /**
  * 进程启动
  */
 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);
 }
开发者ID:bennysuh,项目名称:workerman-game,代码行数:37,代码来源:GameGateway.php

示例10: setUp

 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()));
 }
开发者ID:norbea,项目名称:PhiKettle,代码行数:7,代码来源:KettleTest.php

示例11: __construct

 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);
     }
 }
开发者ID:svgorbunov,项目名称:AcePHProxy,代码行数:7,代码来源:class.client_pool.php

示例12: __construct

 public function __construct($pUrl)
 {
     $this->socket = stream_socket_server($pUrl, $errno, $errstr, STREAM_SERVER_BIND);
     if (!$this->socket) {
         die("{$errstr} ({$errno})");
     }
 }
开发者ID:nagyist,项目名称:extension-tao-devtools,代码行数:7,代码来源:UDPListener.php

示例13: listen

 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);
     });
 }
开发者ID:php-pm,项目名称:php-pm,代码行数:28,代码来源:Server.php

示例14: create

 /**
  * {@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);
 }
开发者ID:icicleio,项目名称:socket,代码行数:34,代码来源:DefaultServerFactory.php

示例15: listen

 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);
     });
 }
开发者ID:mpyw,项目名称:php-hyper-builtin-server,代码行数:25,代码来源:Server.php


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