示例#1
5
 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);
 }
 /**
  * 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
0
 /**
  * Создает сокет и отправляет 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));
 }
 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();
     }
 }
/**
 * 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;
        }
    }
}
 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;
 }
 /**
  * 
  * @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
0
 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
0
 /**
  * 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
0
 /**
  * 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
0
文件: Server.php 项目: beeyev/Socket
 /**
  * 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
0
 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
0
文件: Client.php 项目: LWFeng/hush
 /**
  * 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
0
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
0
 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);
 }
示例#16
0
 public function create()
 {
     $socket = null;
     if (($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
         $errno = socket_last_error();
         throw new RuntimeException('socket_create: ' . socket_strerror($errno), $errno);
     }
     $ret = socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
     $ret = socket_get_option($socket, SOL_SOCKET, SO_KEEPALIVE);
     if ($ret === false) {
         $errno = socket_last_error($socket);
         throw new RuntimeException('socket_get_option SO_KEEPALIVE: ' . socket_strerror($errno), $errno);
     }
     $ret = socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
     $ret = socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR);
     if ($ret === false) {
         $errno = socket_last_error($socket);
         throw new RuntimeException('socket_get_option SO_REUSEADDR: ' . socket_strerror($errno), $errno);
     }
     $ret = socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 5, 'usec' => 0));
     $ret = socket_get_option($socket, SOL_SOCKET, SO_RCVTIMEO);
     if ($ret === false) {
         $errno = socket_last_error($socket);
         throw new RuntimeException('socket_get_option SO_RCVTIMEO: ' . socket_strerror($errno), $errno);
     }
     $ret = socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0));
     $ret = socket_get_option($socket, SOL_SOCKET, SO_SNDTIMEO);
     if ($ret === false) {
         $errno = socket_last_error($socket);
         throw new RuntimeException('socket_get_option SO_SNDTIMEO: ' . socket_strerror($errno), $errno);
     }
     socket_set_nonblock($socket);
     return $socket;
 }
示例#17
0
 function lw_start()
 {
     if ($this->Server['Started'] !== false) {
         return false;
     }
     if (($this->Handler = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
         $this->lw_log('socket_create() failed: reason: ' . socket_strerror(socket_last_error($this->Handler)));
         return false;
     } else {
         $this->lw_log('Socket created');
     }
     socket_set_nonblock($this->Handler);
     if (($ret = socket_bind($this->Handler, $this->Options['Address'], $this->Options['Port'])) !== true) {
         $this->lw_log('socket_bind() failed: reason: ' . socket_strerror(socket_last_error($this->Handler)));
         return false;
     } else {
         $this->lw_log('Socket bindet');
     }
     if (socket_listen($this->Handler, isset($this->Options['ConnectLimit']) ? $this->Options['ConnectLimit'] : 5) !== true) {
         $this->lw_log('socket_listen() failed: reason: ' . socket_strerror(socket_last_error($this->Handler)));
         return false;
     }
     //socket_set_option($this->Handler,SOL_SOCKET,SO_KEEPALIVE,2);
     //echo 'SO_KEEPALIVE	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_KEEPALIVE).RN;
     //echo 'SO_REUSEADDR	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_REUSEADDR).RN;
     //echo 'SO_RCVBUF	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_RCVBUF).RN;
     //echo 'SO_SNDBUF	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_SNDBUF).RN;
     //echo 'SO_DONTROUTE	: '.socket_get_option($this->Handler,SOL_SOCKET,SO_DONTROUTE).RN;
     //echo 'SOCKET_EHOSTUNREACH	: '.SOCKET_EHOSTUNREACH.RN;
     //echo 'SO_BROADCAST : '.socket_get_option($this->Handler,SOL_SOCKET,SO_BROADCAST).RN;
     $this->Server['Started'] = microtime(true);
     /// php 5
     //	wb_create_timer ($_CONTROL['window'], $_SERVER['timer'][0], CL_SOCKET_TIMER);
     return true;
 }
示例#18
0
 /**
  * Connects the TCP socket to the host with the given IP address and port number
  */
 public function connect(InetAddress $ipAddress, $portNumber)
 {
     $this->ipAddress = $ipAddress;
     $this->portNumber = $portNumber;
     if ($this->socketsEnabled) {
         if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
             $errorCode = socket_last_error($this->socket);
             throw new Exception("Could not create socket: " . socket_strerror($errorCode));
         }
         if (@(!socket_connect($this->socket, $ipAddress, $portNumber))) {
             $errorCode = socket_last_error($this->socket);
             throw new Exception("Could not connect socket: " . socket_strerror($errorCode));
         }
         if ($this->isBlocking) {
             socket_set_block($this->socket);
         } else {
             socket_set_nonblock($this->socket);
         }
     } else {
         if (!($this->socket = fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, 2))) {
             throw new Exception("Could not create socket.");
         }
         stream_set_blocking($this->socket, $this->isBlocking);
     }
 }
function server_loop($address, $port)
{
    global $__server_listening;
    // AF_UNIX AF_INET
    if (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
        events("failed to create socket: " . socket_strerror($sock), __FUNCTION__, __LINE__);
        exit;
    }
    if (($ret = socket_bind($sock, $address, $port)) < 0) {
        events("failed to bind socket: " . socket_strerror($ret), __FUNCTION__, __LINE__);
        exit;
    }
    if (($ret = socket_listen($sock, 0)) < 0) {
        events("failed to listen to socket: " . socket_strerror($ret), __FUNCTION__, __LINE__);
        exit;
    }
    socket_set_nonblock($sock);
    events(count($GLOBALS["LOCAL_DOMAINS"]) . " internals domains...", __FUNCTION__, __LINE__);
    events("waiting for clients to connect", __FUNCTION__, __LINE__);
    while ($__server_listening) {
        $connection = @socket_accept($sock);
        if ($connection === false) {
            if ($GLOBALS["DebugArticaFilter"] == 1) {
                events("sleep", __FUNCTION__, __LINE__);
            }
            usleep(2000000);
        } elseif ($connection > 0) {
            handle_client($sock, $connection);
        } else {
            events("error: " . socket_strerror($connection), __FUNCTION__, __LINE__);
            die;
        }
    }
}
示例#20
0
 public function process(LooPHP_EventLoop $event_loop, $timeout)
 {
     $read_resource_array = $this->_socket_array;
     $write_resource_array = NULL;
     $exception_resource_array = $this->_socket_array;
     $results = socket_select($read_resource_array, $write_resource_array, $exception_resource_array, is_null($timeout) ? NULL : floor($timeout), is_null($timeout) ? NULL : fmod($timeout, 1) * 1000000);
     if ($results === FALSE) {
         throw new Exception("stream_select failed");
     }
     if ($results > 0) {
         foreach ($read_resource_array as $read_resource) {
             if ($this->_listen_socket === $read_resource) {
                 $client_resource = @socket_accept($this->_listen_socket);
                 socket_set_nonblock($client_resource);
                 $this->_socket_array[(int) $client_resource] = $client_resource;
                 $this->_socket_data[(int) $client_resource] = array("client_id" => NULL, "buffer" => "");
             } else {
                 $this->readClient($event_loop, $read_resource);
             }
         }
         foreach ($exception_resource_array as $exception_resource) {
             if ($this->_listen_socket === $read_resource) {
                 throw new Exception("listen socket had exception");
             } else {
                 print "Socket had exception\n";
                 unset($this->_socket_array[(int) $exception_resource]);
                 unset($this->_socket_data[(int) $exception_resource]);
             }
         }
     }
     return TRUE;
 }
 public function __construct($logger, $port, $serverip, $serverport)
 {
     $this->logger = $logger;
     $this->port = $port;
     $this->serverip = gethostbyname($serverip);
     $this->serverport = $serverport;
     $this->sendsocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     if (@socket_bind($this->sendsocket, "0.0.0.0", $port) === true) {
         $this->logger->debug("socket open (0.0.0.0 : " . $port . ")");
         $this->logger->info("クライアントから受信したものはすべて " . $serverip . " : " . $serverport . " に送信されます。");
         socket_set_nonblock($this->sendsocket);
     } else {
         $this->working = false;
         $this->logger->info("SendSocketError.(" . $port . ")");
     }
     $this->receivesocket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     $port++;
     if (@socket_bind($this->receivesocket, "0.0.0.0", $port) === true) {
         $this->logger->debug("socket open (0.0.0.0 : " . $port . ")");
         socket_set_nonblock($this->receivesocket);
     } else {
         $this->working = false;
         $this->logger->info("ReceiveSocketError.(" . $port . ")");
     }
     $this->packetanalyze = new PacketAnalyze($this->logger);
     $this->receiveips = [];
 }
示例#22
0
 public function listen($address, $port, $backlog = 5, $throwException = false)
 {
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
     socket_set_nonblock($socket);
     // Binding to a single port
     if (!is_array($address) && !is_array($port)) {
         $success = socket_bind($socket, $address, $port);
     } else {
         // Binding to multiple addresses/ports
         if (is_array($address)) {
             foreach ($address as $_address) {
                 if (is_array($port)) {
                     /*
                     We also need to bind to multiple ports so lets
                     also get that out of the way.
                     */
                     foreach ($port as $_port) {
                         $success = socket_bind($socket, $_address, $_port);
                         /* 
                         We failed to bind to a port, so we're exiting
                         in order to throw an exception.
                         */
                         if ($success !== true) {
                             break 2;
                         }
                     }
                 } else {
                     $success = socket_bind($socket, $_address, $port);
                     if ($success !== true) {
                         break;
                     }
                 }
             }
         } else {
             /* 
             We're not binding to multiple addresses, but we are
             binding to multiple ports.
             */
             foreach ($port as $_port) {
                 $success = socket_bind($socket, $address, $_port);
                 if ($success !== true) {
                     break;
                 }
             }
         }
     }
     if ($success === false) {
         // I know this is ugly, but I didn't want to make the lines too long
         if ($throwException !== false) {
             throw new BindException("Error binding to port {$port}: " . socket_strerror(socket_last_error($socket)));
         } else {
             return false;
         }
     }
     socket_listen($socket, $backlog);
     $this->masterSocket = $socket;
     $this->port = $port;
 }
示例#23
0
 public function __construct()
 {
     $this->_socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     socket_set_nonblock($this->_socket);
     $this->_lastRConTime = microtime(TRUE) + 0.5;
     $this->_valid = array();
     $this->_error = 0;
 }
示例#24
0
 /**
  * ClientSocket constructor.
  *
  * @param $socket
  *
  * @throws NoResourceException
  */
 public function __construct($socket)
 {
     if (!is_resource($socket)) {
         throw new NoResourceException('The given object is no resource.');
     }
     socket_set_nonblock($socket);
     $this->socket = $socket;
 }
示例#25
0
文件: server.php 项目: xqy/php
 function SelectSocketServer()
 {
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($socket === false) {
         exit("socket create fail" . PHP_EOL);
     }
     if (!socket_bind($socket, '127.0.0.1', 1337)) {
         exit("socket blind fail" . PHP_EOL);
     }
     $socket_listen = socket_listen($socket, 10);
     if (!$socket_listen) {
         exit("socket listen fail" . PHP_EOL);
     }
     echo "server start...\n";
     socket_set_nonblock($socket);
     $connections = array();
     while (true) {
         sleep(2);
         $readfds = array_merge($connections, array($socket));
         //$readfds = array();
         $writefds = $connections;
         $errorfds = $connections;
         $select = socket_select($readfds, $writefds, $errorfds, 30);
         if ($select > 0) {
             //如果主socket文件描述符状态有变化,则做连接接收判断
             if (in_array($socket, $readfds)) {
                 echo "check main socket...\n";
                 $newcon = socket_accept($socket);
                 $fid = (int) $newcon;
                 echo date("Y-m-d H:i:s", time()) . "--->client connect...\n";
                 //将客户端连接放入列表里(暂无次数限制)
                 $connections[$fid] = $newcon;
                 $writefds[$fid] = $newcon;
                 $key = array_search($socket, $readfds);
                 unset($readfds[$key]);
             }
             echo "readfds len:" . count($readfds) . "\n";
             foreach ($readfds as $con) {
                 //暂时总长度和单个请求过来的buff一样
                 $recvBuffer = $buff = "";
                 while (!feof($con)) {
                     $buff .= socket_read($con, 8024);
                 }
                 $recvBuffer .= $buff;
                 echo date("Y-m-d H:i:s", time()) . "--->client say:" . $recvBuffer . "\n";
                 if ($this->callback) {
                     call_user_func($this->callback, $con);
                 }
             }
             echo "writefds len:" . count($writefds) . "\n";
             foreach ($writefds as $con) {
                 //暂时啥也不做
                 socket_write($con, "hi " . (int) $con . " client!\n");
             }
         }
     }
 }
示例#26
0
文件: client.php 项目: prggmr/xpspl
 /**
  * Establishes the socket connection.
  *
  * @return  boolean
  */
 protected function _connect()
 {
     $this->_socket = @socket_accept($this->_socket);
     if (false === $this->_socket) {
         return false;
     }
     socket_set_nonblock($this->_socket);
     return true;
 }
示例#27
0
 private function socketConnect($sIp, $iPort)
 {
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_bind($this->socket, $sIp, $iPort);
     socket_set_option($this->socket, SOL_SOCKET, SO_KEEPALIVE, 1);
     socket_set_nonblock($this->socket);
     socket_listen($this->socket, 1000000);
     $this->clientsArray = array($this->socket);
 }
示例#28
0
 public function __construct($resource, $id)
 {
     if (get_resource_type($resource) !== self::RESOURCE_TYPE) {
         throw new \Exception("Unsupported resourse type '" . get_resource_type($resource) . "' received");
     }
     $this->resource = $resource;
     socket_set_nonblock($this->resource);
     $this->id = $id;
 }
示例#29
0
 public function onStart()
 {
     $this->socket = socket_create_listen(10080, SOMAXCONN);
     if ($this->socket == false) {
         throw new RuntimeException("Listening on port 10080 failed: " . socket_last_error());
     }
     socket_set_nonblock($this->socket);
     L::level(L::DEBUG) && L::log(L::DEBUG, __CLASS__, "Installed JSON listener...", array());
 }
示例#30
0
 private function init()
 {
     $this->ListenSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($this->ListenSocket, SOL_SOCKET, SO_REUSEADDR, 1);
     socket_bind($this->ListenSocket, PUSH_SOCKET_LISTEN_ADDRESS, PUSH_SOCKET_LISTEN_PORT);
     socket_listen($this->ListenSocket);
     socket_set_nonblock($this->ListenSocket);
     echo "\nInitialized\n";
 }