本文整理汇总了PHP中socket_set_nonblock函数的典型用法代码示例。如果您正苦于以下问题:PHP socket_set_nonblock函数的具体用法?PHP socket_set_nonblock怎么用?PHP socket_set_nonblock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了socket_set_nonblock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
public function run()
{
$null = NULL;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, $this->host, $this->port);
socket_listen($socket);
socket_set_nonblock($socket);
$this->clients = array($socket);
//start endless loop
while (true) {
$changed = $this->clients;
socket_select($changed, $null, $null, 0, 10);
//check for new socket
if (in_array($socket, $changed)) {
if (($socket_new = socket_accept($socket)) !== false) {
$this->clients[] = $socket_new;
$header = socket_read($socket_new, 1024);
if ($this->handshake($header, $socket_new) === false) {
continue;
}
socket_getpeername($socket_new, $ip);
if (isset($this->events['open'])) {
$this->events['open']($this, $ip);
}
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
}
//loop through all connected sockets
foreach ($changed as $changed_socket) {
//check for any incomming data
while (socket_recv($changed_socket, $buf, 1024, 0) >= 1) {
$received_text = $this->unmask($buf);
//unmask data
$data = json_decode($received_text, true);
//json decode
if (isset($this->events['message'])) {
$this->events['message']($this, $data);
}
break 2;
}
$buf = socket_read($changed_socket, 1024, PHP_NORMAL_READ);
// check disconnected client
if ($buf === false) {
$found_socket = array_search($changed_socket, $this->clients);
socket_getpeername($changed_socket, $ip);
unset($this->clients[$found_socket]);
if (isset($this->events['close'])) {
$this->events['close']($this, $ip);
}
}
}
if ($this->timeout) {
sleep($this->timeout);
}
}
socket_close($socket);
}
示例2: connect
/**
* Connects the TCP socket to the host with the given IP address and port
* number
*
* Depending on whether PHP's sockets extension is loaded, this uses either
* <var>socket_create</var>/<var>socket_connect</var> or
* <var>fsockopen</var>.
*
* @param string $ipAddress The IP address to connect to
* @param int $portNumber The TCP port to connect to
* @param int $timeout The timeout in milliseconds
* @throws SocketException if an error occurs during connecting the socket
*/
public function connect($ipAddress, $portNumber, $timeout)
{
$this->ipAddress = $ipAddress;
$this->portNumber = $portNumber;
if ($this->socketsEnabled) {
if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
throw new SocketException(socket_last_error($this->socket));
}
socket_set_nonblock($this->socket);
@socket_connect($this->socket, $ipAddress, $portNumber);
$write = array($this->socket);
$read = $except = array();
$sec = floor($timeout / 1000);
$usec = $timeout % 1000;
if (!socket_select($read, $write, $except, $sec, $usec)) {
$errorCode = socket_last_error($this->socket);
} else {
$errorCode = socket_get_option($this->socket, SOL_SOCKET, SO_ERROR);
}
if ($errorCode) {
throw new SocketException($errorCode);
}
socket_set_block($this->socket);
} else {
if (!($this->socket = @fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, $timeout / 1000))) {
throw new SocketException($socketErrstr);
}
stream_set_blocking($this->socket, true);
}
}
示例3: request
/**
* Создает сокет и отправляет http запрос
* @param string $url адрес на который отправляется запрос
* @param string $method тип запроса, POST или GET
* @param array $data данные отправляемые при POST запросом
* @return int $id идентификатор запроса
* @return false в случае ошибки
*/
private function request($url, $method = 'GET', $data = array())
{
$parts = parse_url($url);
if (!isset($parts['host'])) {
return false;
}
if (!isset($parts['port'])) {
$parts['port'] = 80;
}
if (!isset($parts['path'])) {
$parts['path'] = '/';
}
if ($data && $method == 'POST') {
$data = http_build_query($data);
} else {
$data = false;
}
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
socket_connect($socket, $parts['host'], $parts['port']);
// Если установить флаг до socket_connect соединения не происходит
socket_set_nonblock($socket);
socket_write($socket, $method . " " . $parts['path'] . '?' . $parts['query'] . " HTTP/1.1\r\n");
socket_write($socket, "Host: " . $parts['host'] . "\r\n");
socket_write($socket, "Connection: close\r\n");
if ($data) {
socket_write($socket, "Content-Type: application/x-www-form-urlencoded\r\n");
socket_write($socket, "Content-length: " . strlen($data) . "\r\n");
socket_write($socket, "\r\n");
socket_write($socket, $data . "\r\n");
}
socket_write($socket, "\r\n");
$this->sockets[] = $socket;
return max(array_keys($this->sockets));
}
示例4: __construct
public function __construct(MasterInfo $master)
{
$this->_socket = @socket_create(AF_INET, SOCK_STREAM, 0);
if ($this->_socket === false) {
throw new Exception("Could not create tcp socket", socket_last_error($this->_socket));
}
$res = @socket_set_nonblock($this->_socket);
if ($res === false) {
throw new Exception("Could not set non blocking socket", socket_last_error($this->_socket));
}
$this->master = $master;
$res = @socket_connect($this->_socket, $master->ip, $master->port);
if ($res === false) {
$error = socket_last_error($this->_socket);
if ($error != SOCKET_EINPROGRESS) {
@socket_close($this->_socket);
throw new Exception("Error connecting to masterserver {$srv->ip}:{$srv->port}", $error);
} else {
$this->isConnecting = true;
}
} else {
$this->isConnecting = false;
$this->sendHeartbeat();
}
}
示例5: server_loop
/**
* Creates a server socket and listens for incoming client connections
* @param string $address The address to listen on
* @param int $port The port to listen on
*/
function server_loop($address, $port)
{
global $__server_listening;
if (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
echo "failed to create socket: " . socket_strerror($sock) . "\n";
exit;
}
if (($ret = socket_bind($sock, $address, $port)) < 0) {
echo "failed to bind socket: " . socket_strerror($ret) . "\n";
exit;
}
if (($ret = socket_listen($sock, 0)) < 0) {
echo "failed to listen to socket: " . socket_strerror($ret) . "\n";
exit;
}
socket_set_nonblock($sock);
echo "waiting for clients to connect\n";
while ($__server_listening) {
$connection = @socket_accept($sock);
if ($connection === false) {
usleep(100);
} elseif ($connection > 0) {
handle_client($sock, $connection);
} else {
echo "error: " . socket_strerror($connection);
die;
}
}
}
示例6: init
public function init()
{
if ($this->initialized) {
return NULL;
}
$this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->socket === false) {
$this->setError($this->getSocketError("Failed creating socket"), LOG_ERR);
return false;
}
if (!socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
$this->setError($this->getSocketError("Failed setting SO_REUSEADDR on socket"), LOG_ERR);
return false;
}
if (!@socket_bind($this->socket, $this->server_address, $this->server_port)) {
$this->setError($this->getSocketError("Failed binding socket to " . $this->server_address . ":" . $this->server_port), LOG_ERR);
return false;
}
if (!@socket_listen($this->socket, 5)) {
$this->setError($this->getSocketError("Failed starting to listen on socket"), LOG_ERR);
return false;
}
socket_set_nonblock($this->socket);
return $this->initialized = true;
}
示例7: __construct
/**
*
* @param type $type
* @param type $port
* @param type $address
* @param type $maxclientsperip
* @param type $maxconnections
*/
public function __construct($type, $port, $address = '0.0.0.0', $max_connperip = 20, $max_clients = 1000)
{
// create socket
$this->socket = socket_create(AF_INET, SOCK_STREAM, 0);
// bind socket
if (!@socket_bind($this->socket, $address, $port)) {
tools::log("Could not bind socket " . $address . ":" . $port);
exit;
// stop script...
}
// listen to socket
socket_listen($this->socket);
// set socket non blocking
socket_set_nonblock($this->socket);
// max connections per ip
$this->max_connperip = $max_connperip;
// max clients for socket
$this->max_clients = $max_clients;
// set type
$this->type = $type;
// load class
include './classes/' . $this->type . '.php';
// log message
tools::log('socket started on ' . $address . ':' . $port . ' with ' . $max_clients . ' clients max');
}
示例8: __construct
public function __construct($host, $port)
{
$ipAddr = self::DEFAULT_IPADDR;
if (false === ip2long($host)) {
$ipAddr = gethostbyname($host);
} else {
$ipAddr = $host;
}
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (false === $socket) {
throw new PhpBuf_RPC_Socket_Exception('socket creation fail:' . socket_strerror(socket_last_error()));
}
$connected = socket_connect($socket, $ipAddr, $port);
if (false === $connected) {
throw new PhpBuf_RPC_Socket_Exception('socket connection fail:' . socket_strerror(socket_last_error()));
}
socket_set_nonblock($socket);
// socket_set_timeout($socket, 5);
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0));
socket_set_option($socket, SOL_SOCKET, SO_LINGER, array('l_onoff' => 1, 'l_linger' => 1));
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
if (defined('TCP_NODELAY')) {
socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1);
}
$this->socket = $socket;
}
示例9: flush
/**
* Squirt the metrics over UDP
*
* @param array $data Incoming Data
* @param int $sampleRate the rate (0-1) for sampling.
* @param array|string $tags Key Value array of Tag => Value, or single tag as string
*
* @return null
*/
private function flush($data, $sampleRate = 1, array $tags = null)
{
// sampling
$sampledData = array();
if ($sampleRate < 1) {
foreach ($data as $stat => $value) {
if (mt_rand() / mt_getrandmax() <= $sampleRate) {
$sampledData[$stat] = "{$value}|@{$sampleRate}";
}
}
} else {
$sampledData = $data;
}
if (empty($sampledData)) {
return;
}
foreach ($sampledData as $stat => $value) {
if ($tags !== NULL && is_array($tags) && count($tags) > 0) {
$value .= '|#';
foreach ($tags as $tag_key => $tag_val) {
$value .= $tag_key . ':' . $tag_val . ',';
}
$value = substr($value, 0, -1);
} elseif (isset($tags) && !empty($tags)) {
$value .= '|#' . $tags;
}
$message = "{$stat}:{$value}";
// Non - Blocking UDP I/O - Use IP Addresses!
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_nonblock($socket);
socket_sendto($socket, $message, strlen($message), 0, $this->server, $this->port);
socket_close($socket);
}
}
示例10: getSocket
/**
* Open a socket if there isn't one open already, return it.
* Returns false on error.
*
* @return false|resource
*/
protected function getSocket()
{
if ($this->socket !== null) {
return $this->socket;
}
$ip = $this->getIP();
if (!$ip) {
$this->log("DNS error");
$this->markDown();
return false;
}
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_nonblock($this->socket);
wfSuppressWarnings();
$ok = socket_connect($this->socket, $ip, $this->port);
wfRestoreWarnings();
if (!$ok) {
$error = socket_last_error($this->socket);
if ($error !== self::EINPROGRESS) {
$this->log("connection error: " . socket_strerror($error));
$this->markDown();
return false;
}
}
return $this->socket;
}
示例11: create
/**
* Create server
* - bind to port
* - listen port
* @throws ListenException
* @throws BindException
*/
function create($blocking = true)
{
$this->open();
$serverSocket = $this->getSocketResource();
if (!socket_bind($serverSocket, $this->getIp(), $this->getPort())) {
throw new BindException($this);
}
$this->getEventDispatcher()->dispatch(BindEvent::getEventName(), new BindEvent($this, $this));
if (!socket_listen($serverSocket)) {
throw new ListenException($this);
}
if ($blocking) {
socket_set_block($serverSocket);
} else {
socket_set_nonblock($serverSocket);
}
$this->start();
while ($this->running) {
$clientSocket = socket_accept($serverSocket);
if (false == $clientSocket) {
continue;
}
$socket = new Socket($this->getAddressType(), $this->getSocketType(), $this->getTransport(), $this->getEventDispatcher());
$socket->setSocketResource($clientSocket);
$socket->getEventDispatcher()->dispatch(NewConnectionEvent::getEventName(), new NewConnectionEvent($socket, $this));
}
}
示例12: start
public function start()
{
self::$_logger->info('Server starts.');
// Init a non-blocking TCP socket for listening
$this->_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$this->_sock) {
$errno = socket_last_error();
$errstr = socket_strerror($errno);
self::$_logger->err("Socket create error: {$errstr} ({$errno})");
die;
}
socket_set_nonblock($this->_sock);
if (!socket_bind($this->_sock, $this->_addr, $this->_port)) {
$errno = socket_last_error();
$errstr = socket_strerror($errno);
self::$_logger->err("Socket bind error: {$errstr} ({$errno})");
die;
}
if (!socket_listen($this->_sock, $this->_listenQueue)) {
$errno = socket_last_error();
$errstr = socket_strerror($errno);
self::$_logger->err("Socket listen error: {$errstr} ({$errno})");
die;
}
// For the listening socket, we use raw event to handle it.
$this->_listenEvent = event_new();
event_set($this->_listenEvent, $this->_sock, EV_READ | EV_PERSIST, array($this, 'handleAcceptEvent'));
event_base_set($this->_listenEvent, $this->_eventBase);
event_add($this->_listenEvent);
// Endless loop
$this->_started = TRUE;
event_base_loop($this->_eventBase);
// The loop ends here.
$this->stop();
}
示例13: send
/**
* Send message package to the socket server
* Basic layer method
*
* @return mixed
*/
public function send($msg, $is_block = false)
{
if (!$this->host || !$this->port) {
throw new Hush_Socket_Exception("Please set server's host and port first");
}
/* Create a TCP/IP socket. */
$this->sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->sock < 0) {
echo "socket_create() failed.\nReason: " . socket_strerror($this->sock) . "\n";
}
$result = @socket_connect($this->sock, $this->host, $this->port);
if ($result < 0) {
echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n";
}
if ($is_block) {
@socket_set_nonblock($this->sock);
}
// add suffix for socket msg
$msg = trim($msg) . "\r\n";
@socket_write($this->sock, $msg, strlen($msg));
$result = @socket_read($this->sock, 2048);
// unserialize data from socket server
$result = unserialize(trim($result));
return $result;
}
示例14: getsock
function getsock($port)
{
$socket = null;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false || $socket === null) {
$error = socket_strerror(socket_last_error());
$msg = "socket create({$port}) failed";
echo "ERR: {$msg} '{$error}'\n";
return NULL;
}
socket_set_nonblock($socket);
$res = socket_connect($socket, API_HOST, $port);
$timeout = 50;
while ($res === false && $timeout > 0) {
$err = socket_last_error($socket);
echo ".";
if ($timeout > 1 && ($err == 115 || $err == 114)) {
$timeout--;
usleep(50);
$res = socket_connect($socket, API_HOST, $port);
continue;
}
$error = socket_strerror($err);
$msg = "socket connect({$port}) failed";
echo "ERR: {$msg} '{$error}'\n";
socket_close($socket);
return NULL;
}
socket_set_block($socket);
return $socket;
}
示例15: SetOptions
function SetOptions()
{
socket_set_option($this->Socket, SOL_SOCKET, SO_KEEPALIVE, 0);
socket_set_option($this->Socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_set_timeout($this->Socket, 2);
socket_set_nonblock($this->Socket);
}