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); }
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; }
/** * 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; }
/** * 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; }
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); } } } }
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); }
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."; } } }
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; } } }
/** * 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; } }
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); }
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); }
/** * 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; } } }
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!'; }
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); } } }
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; }
function run() { while (true) { $changes = $this->sockets; socket_select($changes, $write = NULL, $except = NULL, NULL); foreach ($changes as $sock) { if ($sock == $this->master) { $client = socket_accept($this->master); //$key=uniqid(); $this->sockets[] = $client; $this->users[] = array('socket' => $client, 'shou' => false); } else { $len = socket_recv($sock, $buffer, 2048, 0); $k = $this->search($sock); if ($len < 7) { $name = $this->users[$k]['ming']; $this->close($sock); $this->send2($name, $k); continue; } if (!$this->users[$k]['shou']) { $this->woshou($k, $buffer); } else { $buffer = $this->uncode($buffer); $this->send($k, $buffer); } } } } }
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); }
/** * 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)); } }
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; }
function listen() { while (true) { $changed = $this->sockets; socket_select($changed, $write = NULL, $except = NULL, NULL); foreach ($changed as $socket) { if ($socket == $this->master) { $client = socket_accept($this->master); if ($client < 0) { $this->log("socket_accept() failed"); continue; } else { $this->connect($client); } } else { $bytes = @socket_recv($socket, $buffer, 2048, 0); if ($bytes == 0) { $this->disconnect($socket); } else { $user = $this->getuserbysocket($socket); if (!$user->handshake) { $this->dohandshake($user, $buffer); } else { $this->process($user, $this->unwrap($buffer)); } } } } } }
public static function server() { do { $socket_accept = socket_accept(self::$_socket); if ($socket_accept === FALSE) { self::$_log->error("socket_accept,reason : " . socket_strerror(socket_last_error(self::$_socket)) . "connection with client will be aborted, but accepting new connections... "); continue; } self::$_log->debug("accepting new connection..."); $clientRequest = socket_read($socket_accept, self::$_max_res_serialized_length, PHP_BINARY_READ); if ($clientRequest === FALSE) { self::$_log->error("socket_read,reason : " . socket_strerror(socket_last_error(self::$_socket)) . "connection with client will be aborted, but accepting new connections... "); continue; } self::$_log->debug("data read successfully..."); $serialized_resource_wrapper_s = self::extractWrapper($clientRequest); self::$_log->debug("received serialized <ResourceWrapper> from client :" . $serialized_resource_wrapper_s); $serialized_server_response_s = ResourceManagerImpl::manage($serialized_resource_wrapper_s); self::$_log->debug("serialized <ResponseWrapped> that will be sent to client: " . $serialized_server_response_s); $r = socket_write($socket_accept, $serialized_server_response_s, strlen($serialized_server_response_s)); if ($r === FALSE) { self::$_log->error("socket_write,reason : " . socket_strerror(socket_last_error()) . "connection with client will be aborted, but accepting new connections... "); continue; } self::$_log->debug("serialized <ResponseWrapped> was sent to client: " . $serialized_server_response_s); // @param2 - 1 => block writing in socket ... socket_shutdown($socket_accept, 1); socket_close($socket_accept); } while (TRUE); }
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); }
/** * ソケット待ち受け処理 */ protected function listen() { try { // 通信が来てないかチェック $clientsock = @socket_accept($this->sock); $buf = @socket_read($clientsock, 10240, PHP_NORMAL_READ); if (false !== $buf and '' != $buf) { // 通信が来ている list($topic, $message) = $this->parseBuffer($buf); if (isset($topic) and isset($message)) { // チャットへ発言し正常コードを応答(対象チャットが見つからない場合はSkype_Exceptionが発生) $this->send($topic, $message); socket_write($clientsock, "200\n", 4); } else { // コマンドは受け付けられなかった socket_write($clientsock, "500\n", 4); } } } catch (Skype_Exception $skype_e) { // Skype例外(大抵の場合、チャット名が間違っていて取得できなかった) fputs(STDERR, 'ERROR! Catched Skype_Exception = ' . $skype_e->getMessage() . "\n"); socket_write($clientsock, "501\n", 4); } catch (Exception $e) { // それ以外の例外は標準エラー出力を吐いて続行 fputs(STDERR, 'ERROR! Catched Exception = ' . $e->getMessage() . "\n"); } // 必要があればクライアントのソケットはクローズ if (is_resource($clientsock)) { socket_close($clientsock); } }
public function run() { $null = NULL; while (true) { $changed = $this->allClients; socket_select($changed, $null, $null, 0, 10); foreach ($this->socketServers as $socketServer) { $socket = $socketServer->socket; if (in_array($socket, $changed)) { $newSocket = socket_accept($socket); $this->allClients[] = $newSocket; $socketServer->clients[] = $newSocket; $socketServer->newConnect($newSocket); $foundSocket = array_search($socket, $changed); unset($changed[$foundSocket]); } } foreach ($changed as $changedSocket) { foreach ($this->socketServers as $socketServer) { if (in_array($changedSocket, $socketServer->clients)) { switch ($socketServer->socketChanged($changedSocket)) { case AbstractSocketServer::$INCOMING_DATA: break 2; case AbstractSocketServer::$LOSE_CONNECT: $foundSocket = array_search($changedSocket, $this->allClients); unset($this->allClients[$foundSocket]); break; } } } } } }
protected function serverLoop() { while ($this->_listenLoop) { if (($client = @socket_accept($this->sockServer)) === false) { $info = array(); if (pcntl_sigtimedwait(array(SIGUSR1), $info, 1) > 0) { if ($info['signo'] == SIGUSR1) { $this->handleProcess(); } } continue; } $socketClient = new SocketClientBroadcast($client, $this); if (is_array($this->connectionHandler)) { $object = $this->connectionHandler[0]; $method = $this->connectionHandler[1]; $childPid = $object->{$method}($socketClient); } else { $function = $this->connectionHandler; $childPid = $function($socketClient); } if (!$childPid) { // force child process to exit from loop return; } $this->connections[$childPid] = $socketClient; } }
/** *@name run *@desc wait for the client to connect and process */ public function run() { while (true) { $socketArr = $this->sockets; $write = NULL; $except = NULL; socket_select($socketArr, $write, $except, NULL); //select the socket with message automaticly //if handshake choose the master foreach ($socketArr as $socket) { if ($socket == $this->master) { $client = socket_accept($this->master); if ($client < 0) { $this->log("socket_accept() failed"); continue; } else { $this->connect($client); } } else { $this->log("----------New Frame Start-------"); $bytes = @socket_recv($socket, $buffer, 2048, 0); if ($bytes == 0) { $this->disconnect($socket); } else { $user = $this->getUserBySocket($socket); if (!$user->handshake) { $this->doHandShake($user, $buffer); } else { $this->process($user, $buffer); } } } } } }
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); } }
public function accept() { if (($msgsock = socket_accept($this->socket)) === false) { throw new SocketException(); } return $msgsock; }
public function waitForConnection() { $this->currentClient = socket_accept($this->socket); if (!$this->currentClient) { throw new RuntimeException('Unable to accept connection'); } }
function begin() { while (true) { $changed = $this->sockets; try { socket_select($changed, $write = NULL, $except = NULL, NULL); } catch (exception $e) { echo "Socket Closed"; } foreach ($changed as $socket) { if ($socket == $this->master) { $client = socket_accept($socket); if ($client < 0 || $client === false) { console("socket_accept() failed"); continue; } else { $this->connect($client); } } else { $bytes = @socket_recv($socket, $buffer, 2048, 0); $this->console(bin2hex($buffer)); if ($bytes == 0) { $this->disconnect($socket); } else { $user = $this->getuserbysocket($socket); if (!$user->handshake) { $this->dohandshake($user, $buffer); } else { $this->process($user, $buffer); } } } } } }