Exemplo n.º 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);
 }
Exemplo n.º 2
3
 public function start()
 {
     $host = $this->host;
     $port = $this->port;
     echo "app can be acessed from ws://{$host}:{$port}\n";
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($socket === false) {
         $this->logLastError($socket, "1");
     }
     if (socket_bind($socket, $host, $port) === false) {
         $this->logLastError($socket, "2");
     }
     if (socket_listen($socket, 5) === false) {
         $this->logLastError($socket, "3");
     }
     $this->setServerSocket($socket);
     $serverSocket = $this->getServerSocket();
     do {
         $sockets = $this->getSockets();
         //Set up a blocking call to socket_select
         $write = null;
         $except = null;
         $tv_sec = 5;
         if (socket_select($sockets, $write, $except, $tv_sec) < 1) {
             continue;
         } else {
             $this->setSockets($sockets);
         }
         //Handle new Connections
         if ($this->hasSocket($serverSocket)) {
             $clientSocket = socket_accept($serverSocket);
             if ($clientSocket === false) {
                 $this->logLastError($serverSocket, "4");
             } else {
                 $this->setClientSocket($clientSocket);
                 $response = "HTTP/1.1 101 Switching Protocols";
                 $this->respond($clientSocket, $response);
             }
         }
         //Handle Input
         foreach ($this->getClientSockets() as $clientSocket) {
             if ($this->hasSocket($clientSocket)) {
                 $message = socket_read($clientSocket, 2048, PHP_NORMAL_READ);
                 if ($message === false) {
                     $this->logLastError($clientSocket, "5");
                     $this->removeSocket($clientSocket);
                     socket_close($clientSocket);
                     break;
                 } else {
                     $message = trim($message);
                     if (!empty($message)) {
                         $response = $this->trigger("message", ["{$message}"]);
                         $this->respond($clientSocket, $response);
                     }
                 }
             }
         }
     } while (true);
     socket_close($serverSocket);
 }
 protected function initSyslogServer($logPath, $dataGram = false)
 {
     try {
         if (\file_exists($logPath)) {
             \unlink($logPath);
         }
         if (!file_exists(dirname($logPath))) {
             if (!@mkdir($logPath)) {
                 $this->markTestSkipped('Unable to create log path directory: ' . dirname($logPath));
             }
         }
         if ($dataGram) {
             $this->sock = \socket_create(AF_UNIX, SOCK_DGRAM, 0);
         } else {
             $this->sock = \socket_create(AF_UNIX, SOCK_STREAM, 0);
         }
         \socket_set_option($this->sock, SOL_SOCKET, SO_REUSEADDR, 1);
         \socket_bind($this->sock, $logPath);
         if (!$dataGram) {
             \socket_listen($this->sock);
         }
         $this->logPath = $logPath;
         $this->dataGram = $dataGram;
     } catch (\Exception $e) {
         $this->markTestSkipped('Unable to create log socket at ' . $logPath);
     }
 }
Exemplo n.º 4
0
 public function __construct($MyProperties, $NodeList)
 {
     $this->MyProperties = $MyProperties;
     $this->NodeList = $NodeList;
     $this->Sender = new Sender($this->MyProperties);
     $this->Reciever = new Reciever($this->NodeList);
     $this->state = "Initialized";
     $this->currentTerm = 0;
     $this->votedFor = null;
     $this->votes = 0;
     $this->log = array();
     $this->commitIndex = 0;
     $this->lastApplied = 0;
     $this->lastLogIndex = 0;
     $this->nextIndex = array();
     $this->matchIndex = array();
     $this->timeoutinterval = 0.15;
     $this->heartbeatinterval = 0.075;
     $this->LeaderId = null;
     $this->close = false;
     $this->connectIndex = 0;
     set_time_limit(0);
     $this->socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
     socket_bind($this->socket, $MyProperties->ServerAddr, $MyProperties->PortNo + count($NodeList->Nodes) + 1);
     socket_listen($this->socket);
     $this->clientSocket = false;
     socket_set_nonblock($this->socket);
     $this->exiting = false;
     $this->exitcount = 0;
 }
Exemplo n.º 5
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;
 }
Exemplo n.º 6
0
 /**
  * Create a Socket Server on the given domain and port
  * @param $domain String
  * @param $port Float[optional]
  */
 function create($domain, $port = 9801)
 {
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_bind($this->socket, $domain, $port);
     socket_listen($this->socket);
     socket_set_block($this->socket);
 }
Exemplo n.º 7
0
 /**
  * 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));
     }
 }
Exemplo n.º 8
0
 function __construct($options)
 {
     $this->reset($options);
     pcntl_signal(SIGTERM, array("JAXLHTTPd", "shutdown"));
     pcntl_signal(SIGINT, array("JAXLHTTPd", "shutdown"));
     $options = getopt("p:b:");
     foreach ($options as $opt => $val) {
         switch ($opt) {
             case 'p':
                 $this->settings['port'] = $val;
                 break;
             case 'b':
                 $this->settings['maxq'] = $val;
             default:
                 break;
         }
     }
     $this->httpd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($this->httpd, SOL_SOCKET, SO_REUSEADDR, 1);
     socket_bind($this->httpd, 0, $this->settings['port']);
     socket_listen($this->httpd, $this->settings['maxq']);
     $this->id = $this->getResourceID($this->httpd);
     $this->clients = array("0#" . $this->settings['port'] => $this->httpd);
     echo "JAXLHTTPd listening on port " . $this->settings['port'] . PHP_EOL;
 }
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;
        }
    }
}
Exemplo n.º 10
0
/**
 * 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;
        }
    }
}
Exemplo n.º 11
0
 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;
 }
Exemplo n.º 12
0
 function connect()
 {
     set_time_limit(0);
     fscanf(STDIN, "%d\n", $close);
     //listens for the exit command as a boolean but represented as an integer "1"
     while ($close != 1) {
         // create low level socket
         if (!($socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
             trigger_error('Error creating new socket.', E_USER_ERROR);
         }
         // bind socket to TCP port
         if (!socket_bind($socket, $this->host, $this->port)) {
             trigger_error('Error binding socket to TCP port.', E_USER_ERROR);
         }
         // begin listening connections
         if (!socket_listen($socket)) {
             trigger_error('Error listening socket connections.', E_USER_ERROR);
         }
         // create communication socket
         if (!($comSocket = socket_accept($socket))) {
             trigger_error('Error creating communication socket.', E_USER_ERROR);
         }
         // read socket input
         $socketInput = socket_read($comSocket, 1024);
         // convert to uppercase socket input
         $socketOutput = strtoupper(trim($socketInput)) . "n";
         // write data back to socket server
         if (!socket_write($comSocket, $socketOutput, strlen($socketOutput))) {
             trigger_error('Error writing socket output', E_USER_ERROR);
         }
     }
     close($socket, $comSocket);
 }
Exemplo n.º 13
0
 /**
  * 
  * @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');
 }
 public function __construct($addr, $port, $bufferLength = 2048)
 {
     $this->maxBufferSize = $bufferLength;
     try {
         $this->master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     } catch (Exception $e) {
         $this->stdout($e . 'Failed: socket_create()');
     }
     try {
         socket_set_option($this->master, SOL_SOCKET, SO_REUSEADDR, 1);
     } catch (Exception $e) {
         $this->stdout($e . 'Failed: socket_option()');
     }
     try {
         socket_bind($this->master, $addr, $port);
     } catch (Exception $e) {
         $this->stdout($e . 'Failed: socket_bind()');
     }
     try {
         socket_listen($this->master, 20);
     } catch (Exception $e) {
         $this->stdout($e . 'Failed: socket_listen()');
     }
     $this->sockets['m'] = $this->master;
     $this->stdout("Server started\nListening on: {$addr}:{$port}\nMaster socket: " . $this->master);
 }
 function Server($address = '0', $port = 8001, $verboseMode = false)
 {
     $this->console("Server starting...");
     $this->address = $address;
     $this->port = $port;
     $this->verboseMode = $verboseMode;
     // socket creation
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
     if (!is_resource($socket)) {
         $this->console("socket_create() failed: " . socket_strerror(socket_last_error()), true);
     }
     if (!socket_bind($socket, $this->address, $this->port)) {
         $this->console("socket_bind() failed: " . socket_strerror(socket_last_error()), true);
     }
     if (!socket_listen($socket, 20)) {
         $this->console("socket_listen() failed: " . socket_strerror(socket_last_error()), true);
     }
     $this->master = $socket;
     $this->sockets = array($socket);
     $this->console("Server started on {$this->address}:{$this->port}");
     // Creating a Shared Memory Zone in RAM
     $this->console("Trying to allocate memory");
     $shm_key = ftok(__FILE__, 't');
     $shm_size = 1024 * 1024;
     // 1MB
     $this->shm = shm_attach($shm_key, $shm_size);
     // Launching...
     $this->run();
 }
Exemplo n.º 16
0
 function simple_server($address = 0, $port = 8080, $root = 'htdocs')
 {
     @set_time_limit(0);
     $this->document_root = $root;
     if ($this->pre_init() === false) {
         return false;
     }
     if (($this->socket = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
         return false;
     }
     if (@socket_bind($this->socket, $address, $port) < 0) {
         return false;
     }
     if (@socket_listen($this->socket, 5) < 0) {
         return false;
     }
     #    $this->error_handle = @fopen($this->error_file, "a");
     #    if(!$this->error_handle)
     #      return false;
     #    $this->log_handle = @fopen($this->log_file, "a");
     #    if(!$this->log_handle)
     #      return false;
     if ($this->post_init() === false) {
         return false;
     }
     register_shutdown_function(array(&$this, 'close'));
     return $this->running = true;
 }
Exemplo n.º 17
0
 private function await()
 {
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($sock < 0) {
         echo "Error:" . socket_strerror(socket_last_error()) . "\n";
     }
     $ret = socket_bind($sock, $this->ip, $this->port);
     if (!$ret) {
         echo "BIND FAILED:" . socket_strerror(socket_last_error()) . "\n";
         exit;
     }
     echo "OK\n";
     $ret = socket_listen($sock);
     if ($ret < 0) {
         echo "LISTEN FAILED:" . socket_strerror(socket_last_error()) . "\n";
     }
     do {
         $new_sock = null;
         try {
             $new_sock = socket_accept($sock);
         } catch (Exception $e) {
             echo $e->getMessage();
             echo "ACCEPT FAILED:" . socket_strerror(socket_last_error()) . "\n";
         }
         try {
             $request_string = socket_read($new_sock, 1024);
             $response = $this->output($request_string);
             socket_write($new_sock, $response);
             socket_close($new_sock);
         } catch (Exception $e) {
             echo $e->getMessage();
             echo "READ FAILED:" . socket_strerror(socket_last_error()) . "\n";
         }
     } while (TRUE);
 }
Exemplo n.º 18
0
 public function listen_socket()
 {
     if (socket_listen($this->sock, 5) === false) {
         return false;
     }
     return true;
 }
Exemplo n.º 19
0
 function __construct($host, $port, $root_pw = false)
 {
     ob_start();
     $this->admin_id = false;
     $this->host = $host;
     $this->port = $port;
     if ($root_pw === false) {
         $this->root_pw = uniqid();
     } else {
         $this->root_pw = $root_pw;
     }
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
     if (!is_resource($socket)) {
         $this->console("socket_create() failed: " . socket_strerror(socket_last_error()), true);
         exit;
     }
     if (!socket_bind($socket, $this->host, $this->port)) {
         $this->console("socket_bind() failed: " . socket_strerror(socket_last_error()), true);
         exit;
     }
     if (!socket_listen($socket, 20)) {
         $this->console("socket_listen() failed: " . socket_strerror(socket_last_error()), true);
         exit;
     }
     $this->master = $socket;
     $this->sockets = array($socket);
     $this->mem = new Memcached();
     $this->mem->addServer('127.0.0.1', 11211, 1);
     $this->mem->set('notification-stack', array());
 }
Exemplo n.º 20
0
 public function start()
 {
     //确保在连接客户端时不会超时
     echo "1";
     set_time_limit(0);
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() 建立失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
     //阻塞模式
     echo "2";
     socket_set_block($this->socket) or die("socket_set_block() 阻塞失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
     //绑定到socket端口
     echo "3";
     $result = socket_bind($this->socket, $this->address, 5062) or die("socket_bind() 绑定失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
     //开始监听
     echo "4";
     $result = socket_listen($this->socket, 4) or die("socket_listen() 监听失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
     echo "Begin listining";
     do {
         // never stop the daemon
         //它接收连接请求并调用一个子连接Socket来处理客户端和服务器间的信息
         $msgsock = socket_accept($this->socket) or die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
         //读取客户端数据
         echo "Read client data \n";
         //socket_read函数会一直读取客户端数据,直到遇见\n,\t或者\0字符.PHP脚本把这写字符看做是输入的结束符.
         $buf = socket_read($msgsock, 21000);
         echo "Received msg: {$buf}   \n";
         //数据传送 向客户端写入返回结果
         $msg = "welcome \n";
         socket_write($msgsock, $msg, strlen($msg)) or die("socket_write() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
         //一旦输出被返回到客户端,父/子socket都应通过socket_close($msgsock)函数来终止
         socket_close($msgsock);
     } while (true);
     socket_close($this->socket);
 }
Exemplo n.º 21
0
 /**
  * Começa a escutar conexões e processar as demais funcionalidades
  * @param int $port número da porta
  * @throws EndPointException
  */
 public function listen($port)
 {
     $this->port = $port;
     /* @var resource cria o socket que escutará conexões */
     $this->serverSocket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('TCP'));
     if (!socket_set_option($this->serverSocket, SOL_SOCKET, SO_REUSEADDR, 1)) {
         echo socket_strerror(socket_last_error($this->serverSocket));
         exit;
     }
     /* seta o host e a porta */
     if (!@socket_bind($this->serverSocket, 0, $this->port)) {
         throw new EndPointException("socket_bind() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket)));
     }
     /* inicia a escuta de conexões */
     if (!@socket_listen($this->serverSocket)) {
         throw new EndPointException("socket_listen() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket)));
     }
     /* cria um array de sockets e adiciona o serverSocket no array */
     $this->sockets = array($this->serverSocket);
     $this->loopPrincipal();
     /* Fecha todos os sockets e encerra a aplicação */
     foreach ($this->sockets as $socket) {
         if (get_resource_type($socket) == "Socket") {
             socket_close($socket);
         }
     }
 }
Exemplo n.º 22
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();
 }
Exemplo n.º 23
0
 private function createSocket()
 {
     $this->serverSocket = socket_create(AF_INET, SOCK_STREAM, 0);
     socket_bind($this->serverSocket, 0, $this->port) or die("bind error !!");
     socket_listen($this->serverSocket);
     $this->waitSocket();
 }
Exemplo n.º 24
0
 function connect()
 {
     //set_time_limit(0);
     // create low level socket
     if (!($socket = socket_create(AF_INET, SOCK_STREAM, 0))) {
         trigger_error('Error creating new socket.', E_USER_ERROR);
     }
     // bind socket to TCP port
     if (!socket_bind($socket, $this->host, $this->port)) {
         trigger_error('Error binding socket to TCP port.', E_USER_ERROR);
     }
     // begin listening connections
     if (!socket_listen($socket)) {
         trigger_error('Error listening socket connections.', E_USER_ERROR);
     }
     // create communication socket
     if (!($comSocket = socket_accept($socket))) {
         trigger_error('Error creating communication socket.', E_USER_ERROR);
     }
     // read socket input
     //while ( 1 ) {
     $socketInput = socket_read($comSocket, 1024);
     // convert to uppercase socket input
     $socketOutput = strtoupper(trim($socketInput)) . "n";
     // write data back to socket server
     if (!socket_write($comSocket, $socketOutput, strlen($socketOutput))) {
         trigger_error('Error writing socket output', E_USER_ERROR);
     }
     //}
     // close sockets
     socket_close($comSocket);
     socket_close($socket);
 }
Exemplo n.º 25
0
 /**
  * Start listening
  * 
  * @return Socket the current object, for chaning
  */
 public function listen()
 {
     if (!socket_listen($this->socket, $this->options['backlog'])) {
         throw new SocketException();
     }
     return $this;
 }
Exemplo n.º 26
0
function create_connection($host, $port)
{
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!is_resource($socket)) {
        echo 'Unable to create socket: ' . socket_strerror(socket_last_error()) . PHP_EOL;
    } else {
        echo "Socket created.\n";
    }
    if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
        echo 'Unable to set option on socket: ' . socket_strerror(socket_last_error()) . PHP_EOL;
    } else {
        echo "Set options on socket.\n";
    }
    if (!socket_bind($socket, $host, $port)) {
        echo 'Unable to bind socket: ' . socket_strerror(socket_last_error()) . PHP_EOL;
    } else {
        echo "Socket bound to port {$port}.\n";
    }
    if (!socket_listen($socket, SOMAXCONN)) {
        echo 'Unable to listen on socket: ' . socket_strerror(socket_last_error());
    } else {
        echo "Listening on the socket.\n";
    }
    while (true) {
        $connection = @socket_accept($socket);
        if ($connection) {
            echo "Client {$connection} connected!\n";
            send_data($connection);
        } else {
            echo "Bad connection.";
        }
    }
}
Exemplo n.º 27
0
	function listenForClients()
	{
		$this->serviceConnection = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
		socket_bind($this->serviceConnection, $this->serviceHost, $this->servicePort);
		socket_listen($this->serviceConnection, 10);
		
		echo 'LISTENING ',$this->servicePort,"\n";
		
		while($clientSocket = socket_accept($this->serviceConnection))
		{
			socket_write($clientSocket, "OK\n");
			
			$deviceToken = trim(socket_read($clientSocket, 512, PHP_NORMAL_READ));
			$message = trim(socket_read($clientSocket, 512, PHP_NORMAL_READ));
			
			if(!empty($deviceToken) && !empty($message))
			{

				$this->sendNotification($deviceToken, $message);
				socket_write($clientSocket, "SENT\n");
			}
			else
			{
				socket_write($clientSocket, "ERROR\n");
			}
			socket_close($clientSocket);
		}
	}
Exemplo n.º 28
0
 public static function start()
 {
     if (self::$_initialized === TRUE) {
         $fatalMsg = "server was already initialized";
         self::$_log->fatal($fatalMsg);
         throw new Exception($fatalMsg);
     }
     self::init();
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($socket === FALSE) {
         $fatalMsg = "socket_create, reason : " . socket_strerror(socket_last_error());
         self::$_log->fatal($fatalMsg);
         throw new Exception($fatalMsg);
     }
     self::$_log->info("socket created successfully...");
     $r = socket_bind($socket, self::$_server_addr, self::$_server_port);
     if ($r === FALSE) {
         $fatalMsg = "socket_bind, reason : " . socket_strerror(socket_last_error($socket));
         self::$_log->fatal($fatalMsg);
         throw new Exception($fatalMsg);
     }
     self::$_log->info("socket binded successfully...");
     $r = socket_listen($socket, self::$_max_backlog);
     if ($r === FALSE) {
         $fatalMsg = "socket_listen, reason : " . socket_strerror(socket_last_error($socket));
         self::$_log->fatal($fatalMsg);
         throw new Exception($fatalMsg);
     }
     self::$_log->info("socket listening successfully...");
     self::$_socket = $socket;
     self::server();
     self::$_log->info("server started successfully...");
 }
Exemplo n.º 29
0
 public function __construct(Server $server, $password, $port = 19132, $interface = "0.0.0.0", $threads = 1, $clientsPerThread = 50)
 {
     $this->server = $server;
     $this->workers = [];
     $this->password = (string) $password;
     $this->server->getLogger()->info("Starting remote control listener");
     if ($this->password === "") {
         $this->server->getLogger()->critical("RCON can't be started: Empty password");
         return;
     }
     $this->threads = (int) max(1, $threads);
     $this->clientsPerThread = (int) max(1, $clientsPerThread);
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)) {
         $this->server->getLogger()->critical("RCON can't be started: " . socket_strerror(socket_last_error()));
         $this->threads = 0;
         return;
     }
     socket_set_block($this->socket);
     for ($n = 0; $n < $this->threads; ++$n) {
         $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread);
     }
     socket_getsockname($this->socket, $addr, $port);
     $this->server->getLogger()->info("RCON running on {$addr}:{$port}");
 }
Exemplo n.º 30
0
 public function __construct($host, $port)
 {
     $this->host = $host;
     $this->port = $port;
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
     socket_bind($sock, 0, $this->port);
     socket_listen($sock);
     $clients = array($sock);
     while (true) {
         $read = $clients;
         if (socket_select($read, $write = null, $except = null, 0) < 1) {
             continue;
         }
         if (in_array($sock, $read)) {
             $clients[] = $newSocket = socket_accept($sock);
             $this->handShake($newSocket);
             socket_getpeername($newSocket, $ip);
             $this->send(array('type' => 'system', 'message' => $ip . ' Connected'), $clients);
             echo "New client connected: {$ip}\n";
             $key = array_search($sock, $read);
             unset($read[$key]);
         }
         foreach ($read as $read_sock) {
             while (socket_recv($read_sock, $buf, 1024, 0) >= 1) {
                 $msg = json_decode($this->unmask($buf), true);
                 $this->send($msg, $clients);
             }
         }
     }
     socket_close($sock);
 }