本文整理汇总了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);
}
示例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]);
}
}
}
}
}
}
}
示例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;
}
示例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;
}
示例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);
}
}
}
}
示例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;
}
}
示例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 = [];
}
示例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'));
}
示例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);
}
示例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()));
}
示例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);
}
}
示例12: __construct
public function __construct($pUrl)
{
$this->socket = stream_socket_server($pUrl, $errno, $errstr, STREAM_SERVER_BIND);
if (!$this->socket) {
die("{$errstr} ({$errno})");
}
}
示例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);
});
}
示例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);
}
示例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);
});
}