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


PHP socket_listen函数代码示例

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


在下文中一共展示了socket_listen函数的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);
 }
开发者ID:nicklasos,项目名称:websockets,代码行数:59,代码来源:WebSocket.php

示例2: start

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

示例3: initSyslogServer

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

示例4: __construct

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

示例5: lw_start

 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;
 }
开发者ID:roxblnfk,项目名称:MazePHP,代码行数:35,代码来源:CLASS+rxnetsvlw.php

示例6: create

 /**
  * 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);
 }
开发者ID:vietlethanh,项目名称:KooKooBackEnd,代码行数:12,代码来源:socket.class.php

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

示例8: __construct

 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;
 }
开发者ID:pavl00,项目名称:Kalkun,代码行数:25,代码来源:jaxl.httpd.php

示例9: server_loop

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;
        }
    }
}
开发者ID:BillTheBest,项目名称:1.6.x,代码行数:34,代码来源:exec.artica-filter-daemon.php

示例10: 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;
        }
    }
}
开发者ID:rsbauer,项目名称:KismetServerSimulator,代码行数:34,代码来源:kismetsim.php

示例11: 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;
 }
开发者ID:gutza,项目名称:octave-daemon,代码行数:25,代码来源:Octave_server_socket.php

示例12: connect

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

示例13: __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');
 }
开发者ID:derkalle4,项目名称:gamespy-loginserver,代码行数:33,代码来源:tcp_socket.php

示例14: __construct

 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);
 }
开发者ID:rrgraute,项目名称:php_mvc-ws-cli-memdb,代码行数:26,代码来源:WebSocketServer.php

示例15: Server

 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();
 }
开发者ID:thefkboss,项目名称:ZenTracker,代码行数:30,代码来源:websocketdaemonTask.class.php


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