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


PHP socket_accept函数代码示例

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


在下文中一共展示了socket_accept函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: 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

示例2: process

 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");
     } else {
         if ($results > 0) {
             foreach ($read_resource_array as $read_resource) {
                 if ($this->_listen_socket === $read_resource) {
                     $client_resource = @socket_accept($this->_listen_socket);
                     $this->_socket_array[(int) $client_resource] = $client_resource;
                 } else {
                     //send http responce in 5 second (just to demo events)
                     $event_loop->addEvent(function () use($read_resource) {
                         $send_data = "HTTP/1.0 200 OK\n" . "Content-Type: text/html\n" . "Server: LooPHP" . "\r\n\r\n" . "<body>Hello World</body>";
                         socket_write($read_resource, $send_data);
                         socket_close($read_resource);
                     }, 5);
                     unset($this->_socket_array[(int) $read_resource]);
                 }
             }
             foreach ($exception_resource_array as $exception_resource) {
                 print "Socket had exception\n";
                 unset($this->_socket_array[(int) $exception_resource]);
             }
         }
     }
     return TRUE;
 }
开发者ID:Wordi,项目名称:LooPHP,代码行数:32,代码来源:sockets.php

示例3: connect

 /**
  * Waits for incoming connections.
  */
 public function connect(array $connections, $options)
 {
     $dummy = array();
     $connections[] = $this->sock;
     $ready = @socket_select($connections, $dummy, $dummy, $options['poll_interval']);
     if ($ready === false) {
         throw new StupidHttp_NetworkException("Failed to monitor incoming connections.");
     }
     if ($ready == 0) {
         return null;
     }
     // Check for a new connection.
     $i = array_search($this->sock, $connections);
     if ($i !== false) {
         // Remove our socket from the connections and replace it
         // with the file-descriptor for the new client.
         unset($connections[$i]);
         if (($msgsock = @socket_accept($this->sock)) === false) {
             throw new StupidHttp_NetworkException("Failed accepting connection: " . socket_strerror(socket_last_error($this->sock)));
         }
         if (@socket_set_option($msgsock, SOL_SOCKET, SO_REUSEADDR, 1) === false) {
             throw new StupidHttp_NetworkException("Failed setting address re-use option: " . socket_strerror(socket_last_error($msgsock)));
         }
         $timeout = array('sec' => $options['timeout'], 'usec' => 0);
         if (@socket_set_option($msgsock, SOL_SOCKET, SO_RCVTIMEO, $timeout) === false) {
             throw new StupidHttp_NetworkException("Failed setting timeout value: " . socket_strerror(socket_last_error($msgsock)));
         }
         $connections[] = $msgsock;
     }
     return $connections;
 }
开发者ID:omnicolor,项目名称:bulletphp-site,代码行数:34,代码来源:SocketNetworkHandler.php

示例4: process

 /**
  * Socket processing iteration:
  * accepting client connections,
  * processing client messages
  */
 public function process()
 {
     $numChanged = socket_select($this->_read, $empty, $empty, 0, 10);
     if ($numChanged) {
         if (in_array($this->_serverSocket, $this->_read)) {
             if (count($this->_clientSockets) < $this->_maxClients) {
                 $this->_clientSockets[] = socket_accept($this->_serverSocket);
             }
         }
         foreach ($this->_clientSockets as $key => $client) {
             if (in_array($client, $this->_read)) {
                 $input = socket_read($client, 1024);
                 if ($input === false) {
                     socket_shutdown($client);
                     unset($this->_clientSockets[$key]);
                 } else {
                     if ($input && false !== ($MessageContainer = unserialize($input))) {
                         foreach ($this->_listeners as $Listener) {
                             $Listener->receive($MessageContainer->getMessage());
                         }
                     }
                     socket_close($client);
                     unset($this->_clientSockets[$key]);
                 }
             }
         }
     }
     $this->_read = $this->_clientSockets;
     $this->_read[] = $this->_serverSocket;
 }
开发者ID:jack-po,项目名称:php-multiprocessing,代码行数:35,代码来源:Server.php

示例5: mainLoop

 private function mainLoop()
 {
     $changed_sockets = $this->allsockets;
     @socket_select($changed_sockets, $write = null, $exceptions = null, 0);
     foreach ($this->apps as $app) {
         $app->onTick();
     }
     foreach ($changed_sockets as $socket) {
         if ($socket == $this->master) {
             if (($rec = socket_accept($this->master)) < 0) {
                 $this->log("Error: Could not connect\n" . socket_strerror(socket_last_error($rec)));
                 continue;
             } else {
                 $this->log("New client connecting...");
                 $client = new Connection($this, $rec);
                 $this->clients[$rec] = $client;
                 $this->allsockets[] = $rec;
             }
         } else {
             $client = $this->clients[$socket];
             $bytes = @socket_recv($socket, $data, 4096, 0);
             if (!$bytes) {
                 $client->onDisconnect();
                 unset($this->clients[$socket]);
                 $index = array_search($socket, $this->allsockets);
                 unset($this->allsockets[$index]);
                 unset($client);
             } else {
                 $client->onData($data);
             }
         }
     }
 }
开发者ID:jipengxiang,项目名称:phpWebService,代码行数:33,代码来源:websocket.server.php

示例6: connect

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

示例7: create_connection

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.";
        }
    }
}
开发者ID:ryanstewart,项目名称:PHP-Socket-Demo,代码行数:33,代码来源:socket_quotes.php

示例8: 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

示例9: novaConexao

 /**
  * Checa se o $serverSocket está na lista dos "ouvintes" e realiza os procedimentos para uma nova conexão
  * @param array<resources> $changedSockets array de sockets
  * @return boolean Se houve uma nova conexão ou não
  * @throws EndPointException
  */
 private function novaConexao(&$changedSockets)
 {
     if (in_array($this->serverSocket, $changedSockets)) {
         /* aceita a nova conexão e cria um socket para a seção com este novo usuário */
         $socketNovo = socket_accept($this->serverSocket);
         if (!$socketNovo) {
             throw new EndPointException("socket_accept() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket)));
         }
         /* adiciona o novo socket no array de sockets */
         $this->sockets[] = $socketNovo;
         /* lê os primeiros dados enviados pelo WebSocket do browser, responsáveis pelo 'handshaking' */
         $header = socket_read($socketNovo, 1024);
         if ($header == "") {
             return FALSE;
         }
         //logServidor("\n$header\n");
         /* realiza o processo de 'handshaking' entre o cliente e o servidor */
         $this->performHandshaking($header, $socketNovo);
         /* obtêm o endereço de IP do novo socket 
         	    socket_getpeername($socketNovo, $ip);
         
         	    /* Registra novo socket conectado no array de sockets sem sala, do controlador de salas 
         	    ControladorSalas::addNotGameSocket($socketNovo);
         	    logServidor("\nIp $ip solicita conexão\n");*/
         /* enviar as salas disponíveis ao solicitante */
         //enviaDadoSocket(array('type' => 'login', 'subtype' => 'init', 'listaInfoSalas' => ControladorSalas::geraInfoSalas()), $socketNovo);
         /* remove o $serverSocket da lista de sockets "ouvintes", pois já foi tratado */
         $foundSocket = array_search($this->serverSocket, $changedSockets);
         unset($changedSockets[$foundSocket]);
         return TRUE;
     } else {
         return FALSE;
     }
 }
开发者ID:rubensm1,项目名称:fractal,代码行数:40,代码来源:WebSocket.php

示例10: run

 public function run()
 {
     if ($this->create_socket()) {
         if ($this->bind_socket()) {
             if (!$this->listen_socket()) {
                 return;
             }
         } else {
             return;
         }
     } else {
         return;
     }
     do {
         if (($msgsock = socket_accept($this->sock)) === false) {
             break;
         }
         /*$msg = "\nWelcome to the PHP Test Server. \n" .
               "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
           socket_write($msgsock, $msg, strlen($msg));*/
         do {
             if (false === ($data = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
                 //echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
                 break 2;
             }
             //save data here
             $talkback = "PHP: You said '{$data}'.\n";
             socket_write($msgsock, $talkback, strlen($talkback));
             echo "{$data}\n";
         } while (true);
         socket_close($msgsock);
     } while (true);
 }
开发者ID:hivaids2512,项目名称:nodeManagerWeb,代码行数:33,代码来源:TcpServer.php

示例11: start

 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);
 }
开发者ID:song-yuan,项目名称:wymenujp,代码行数:33,代码来源:SocketServer.php

示例12: 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

示例13: run

 function run()
 {
     //得到客户端的socket,并与之通讯!
     do {
         if (($remote_socket = socket_accept($this->socket)) === false) {
             echo 'socket_accept() failed!  reason:' . socket_strerror(socket_last_error($this->socket));
             continue;
         }
         $message = '<h1 style="color:cyan"> welcome!</h1>';
         socket_write($remote_socket, $message, strlen($message));
         //第一次接入,发送欢迎消息
         echo 'read client message!';
         $buf = socket_read($remote_socket, 8192);
         echo 'message:' . $buf;
         $reply = 'server has receive your message:' . $buf;
         if (socket_write($remote_socket, $reply, strlen($reply)) === false) {
             echo 'socket_write() failed!  reason:' . socket_strerror(socket_last_error($remote_socket));
             continue;
         } else {
             echo 'success!';
             socket_close($remote_socket);
         }
     } while (true);
     socket_close($this->socket);
     echo 'server shutdown!';
 }
开发者ID:keensting,项目名称:KeenSting,代码行数:26,代码来源:server.php

示例14: onSocketsAlterados

 protected function onSocketsAlterados($socketsRead, $socketsWrite, $socketsExcept)
 {
     // Caso socket principal foi alterado (Receptor de conexões)
     if (in_array($this->socketPrincipal, $socketsRead)) {
         $socket = socket_accept($this->socketPrincipal);
         if ($socket != null) {
             $cabecalho = socket_read($socket, 1024);
             $this->tratarSolicitacaoDeConexao($cabecalho, $socket);
         }
         // Retira socket ouvinte de lista de socketsAlterados
         $chave = array_search($this->socketPrincipal, $socketsRead);
         unset($socketsRead[$chave]);
     }
     foreach ($socketsRead as $socketRead) {
         // Verifica mensagens recebidas
         while (socket_recv($socketRead, $buffer, 1024, 0) >= 1) {
             $this->tratarRecebimentoDeMensagem($buffer, $socketRead);
             break 2;
         }
         // Verifica se cliente continua conectado
         $buffer = @socket_read($socketRead, 1024, PHP_NORMAL_READ);
         if ($buffer === false) {
             $this->tratarDesconexao($socketRead);
         }
     }
 }
开发者ID:Franciscofc1986,项目名称:ProjetoGPS,代码行数:26,代码来源:ServidorWSBase.php

示例15: accept_connection

 public function accept_connection()
 {
     $cSocket = @socket_accept($this->socket);
     // We're running non-blocking, so this just means that
     // nobody's knocking
     if ($cSocket === false) {
         return NULL;
     }
     if ($cSocket < 0) {
         $this->setError($this->getSocketError("Failed accepting connection"), LOG_ERR);
         socket_close($cSocket);
         return false;
     }
     if (!@socket_getpeername($cSocket, $remote_IP)) {
         $this->setError($this->getSocketError("Failed retrieving the remote IP address"), LOG_WARNING);
         socket_close($cSocket);
         return false;
     }
     // IP filtering, if enabled
     if (!$this->allow_ip($remote_IP)) {
         Octave_logger::log("Connection attempt from " . $remote_IP);
         socket_close($cSocket);
         return NULL;
     }
     return $cSocket;
 }
开发者ID:gutza,项目名称:octave-daemon,代码行数:26,代码来源:Octave_server_socket.php


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