Exemplo n.º 1
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);
 }
Exemplo n.º 2
2
 function http_request($host, $data)
 {
     if (!($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
         echo "socket_create() error!\r\n";
         exit;
     }
     if (!socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, 1)) {
         echo "socket_set_option() error!\r\n";
         exit;
     }
     if (!socket_connect($socket, $host, 80)) {
         echo "socket_connect() error!\r\n";
         exit;
     }
     if (!socket_write($socket, $data, strlen($data))) {
         echo "socket_write() errror!\r\n";
         exit;
     }
     while ($get = socket_read($socket, 1024, PHP_NORMAL_READ)) {
         $content .= $get;
     }
     socket_close($socket);
     $array = array('HTTP/1.1 404 Not Found', 'HTTP/1.1 300 Multiple Choices', 'HTTP/1.1 301 Moved Permanently', 'HTTP/1.1 302 Found', 'HTTP/1.1 304 Not Modified', 'HTTP/1.1 400 Bad Request', 'HTTP/1.1 401 Unauthorized', 'HTTP/1.1 402 Payment Required', 'HTTP/1.1 403 Forbidden', 'HTTP/1.1 405 Method Not Allowed', 'HTTP/1.1 406 Not Acceptable', 'HTTP/1.1 407 Proxy Authentication Required', 'HTTP/1.1 408 Request Timeout', 'HTTP/1.1 409 Conflict', 'HTTP/1.1 410 Gone', 'HTTP/1.1 411 Length Required', 'HTTP/1.1 412 Precondition Failed', 'HTTP/1.1 413 Request Entity Too Large', 'HTTP/1.1 414 Request-URI Too Long', 'HTTP/1.1 415 Unsupported Media Type', 'HTTP/1.1 416 Request Range Not Satisfiable', 'HTTP/1.1 417 Expectation Failed', 'HTTP/1.1 Retry With');
     for ($i = 0; $i <= count($array); $i++) {
         if (eregi($array[$i], $content)) {
             return "{$array[$i]}\r\n";
             break;
         } else {
             return "{$content}\r\n";
             break;
         }
     }
 }
Exemplo n.º 3
0
 private function ReadBlockFromSocket($socket)
 {
     // read until newline or 30000 bytes
     // socket_read will show errors when the client is disconnected, so silence the error messages
     //LogWrite("ReadBlockFromSocket: begin");
     $res = "";
     do {
         $data = @socket_read($socket, 30000, PHP_NORMAL_READ);
         if ($data === false) {
             if ($res != "") {
                 //LogWrite("ReadBlockFromSocket-false: end - res: $res");
                 return $res;
             } else {
                 //LogWrite("ReadBlockFromSocket-false: end - false");
                 return false;
             }
         }
         //LogWrite("ReadBlockFromSocket-addData: " . strlen($data));
         $res .= $data;
         $cnt = substr_count($res, '"');
         //LogWrite("cnt: " . $cnt);
     } while ($cnt != 0 && $cnt % 2 != 0);
     // trim off the trailing/beginning white spaces
     $res = trim($res);
     //LogWrite("ReadBlockFromSocket: end - $res");
     return $res;
 }
Exemplo n.º 4
0
 function read()
 {
     $buff = socket_read($this->_socket, 1024);
     $resarray = explode("", $buff);
     $removed = array_shift($resarray);
     $rescount = count($resarray);
     if ($rescount != 0) {
         foreach ($resarray as $k => $v) {
             $rcvd_type = $this->_identify($v);
             echo "<h3> {$rcvd_type} </h3>";
             if ($rcvd_type == 'msg') {
                 $msg = $this->parse_received_message($v);
                 print_r($msg);
                 // Do something with the message here ?
             } else {
                 if ($rcvd_type == 'account_info') {
                     $accinfo = $this->parse_account_info($v);
                     print_r($accinfo);
                     // They're stored in account variables too
                 } else {
                     if ($rcvd_type == 'last_seen') {
                         $lastseen = $this->parse_last_seen($v);
                         print_r($lastseen);
                         // They're stored in account variables too
                     }
                 }
             }
         }
         unset($rcvd_type);
     }
     echo $buff . "<br /><br /><br /><br /><br /><br /><br />";
     return $buff;
 }
Exemplo n.º 5
0
 public function flushAll()
 {
     $result = true;
     foreach ($this->servers as $server) {
         if (count(explode('.', $server['ip']) == 3)) {
             $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
         } else {
             $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
         }
         // generate the raw http request
         $command = sprintf("GET %s HTTP/1.1\r\n", $this->router->generate('sonata_page_apc_cache', array('token' => $this->token)));
         $command .= sprintf("Host: %s\r\n", $server['domain']);
         $command .= "Connection: Close\r\n\r\n";
         // setup the default timeout (avoid max execution time)
         socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 2, 'usec' => 0));
         socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0));
         socket_connect($socket, $server['ip'], $server['port']);
         socket_write($socket, $command);
         $content = socket_read($socket, 1024);
         if ($result) {
             $result = substr($content, -2) == 'ok' ? true : false;
         }
     }
     return $result;
 }
Exemplo n.º 6
0
function sock_read(&$sock, $length = 1024)
{
    $sock->error = "";
    $sock->errno = 0;
    $data = socket_read($sock->socket, $length);
    if (strlen($data) < $length) {
        $left = $length - strlen($data);
        $errs = 0;
        while ($left > 0 && $errs < 5) {
            $oldleft = $left;
            $part = socket_read($sock->socket, $left);
            if ($part !== false && strlen($part) > 0) {
                $data .= $part;
                $left = $length - strlen($data);
            } elseif ($part === false) {
                $left = 0;
            } else {
                $errs++;
            }
        }
        if ($errs >= 5) {
            $sock->error = "Socket read error";
            $sock->errno = 0;
        }
    }
    return $data;
}
Exemplo n.º 7
0
function ft_init($socket, $tbl)
{
    $out = socket_read($socket, 2048);
    echo $out;
    socket_write($socket, $tbl["team"] . "\n");
    $out = socket_read($socket, 2048);
    echo $out;
    $tbl = explode("\n", $out);
    if ($tbl[1]) {
        $result = array();
        $tbl2 = explode(' ', $tbl[1]);
        $result['x'] = $tbl2[0];
        $result['y'] = $tbl2[1];
        $map = array();
        for ($y = 0; $y < $result['y']; $y++) {
            $map[$y] = array();
            for ($x = 0; $x < $result['x']; $x++) {
                $map[$y][$x] = 0;
            }
        }
        $map["size"] = $result;
        return $map;
    }
    ft_error("init map", TRUE);
}
Exemplo n.º 8
0
 protected function _checkClosedRequests()
 {
     foreach ($this->_clients as $key => $client) {
         if (in_array($client, $this->_read)) {
             $buf = @socket_read($client, 1024, PHP_NORMAL_READ);
             if ($buf === false) {
                 throw new Exception\Listener(socket_strerror(socket_last_error($client)));
             }
             $buf = trim($buf);
             if ($buf) {
                 switch ($buf) {
                     case 'quit':
                         print "Close connection\n";
                         unset($this->_clients[$key]);
                         $this->_requests[$key]->finished = true;
                         unset($this->_requests[$key]);
                         socket_close($client);
                         break;
                     case 'shutdown':
                         throw new Exception\Listener('Shutdown detected');
                 }
             }
         }
     }
     return true;
 }
Exemplo n.º 9
0
 protected function handleRead($read_sock)
 {
     // read until newline or 1024 bytes
     // socket_read while show errors when the client is disconnected, so silence the error messages
     $data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);
     // check if the client is disconnected
     if ($data === false) {
         // remove client for $this->clients array
         $key = array_search($read_sock, $this->clients);
         unset($this->clients[$key]);
         echo "client disconnected.\n";
         // continue to the next client to read from, if any
         continue;
     }
     // trim off the trailing/beginning white spaces
     $data = trim($data);
     // check if there is any data after trimming off the spaces
     if (!empty($data)) {
         // send this to all the clients in the $this->clients array (except the first one, which is a listening socket)
         foreach ($this->clients as $send_sock) {
             // if its the listening sock or the client that we got the message from, go to the next one in the list
             if ($send_sock == $this->sock || $send_sock == $read_sock) {
                 continue;
             }
             // write the message to the client -- add a newline character to the end of the message
             socket_write($send_sock, $data . "\n");
         }
     }
 }
Exemplo n.º 10
0
 public function send($data)
 {
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($socket == null) {
         return false;
     }
     socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $this->timeout, 'usec' => 0));
     if (!socket_connect($socket, $this->host, $this->port)) {
         return false;
     }
     $packed = json_encode($data);
     echo $packed;
     //Write Header
     socket_write($socket, "ZBXD");
     //Write Data length
     $length = strlen($packed);
     socket_write($socket, pack("V*", $length, $length >> 32));
     socket_write($socket, $packed);
     $return_header = socket_read($socket, 5);
     $return_length = unpack("V*", socket_read($socket, 8));
     $return_length = $return_length[1] + ($return_length[2] << 32);
     $return_data = socket_read($socket, $return_length);
     $return_data = json_decode($return_data);
     socket_close($socket);
     return $return_data;
 }
Exemplo n.º 11
0
function socket_normal_read($socket)
{
    global $config, $sockets, $queues, $sock_num;
    for ($i = 0; isset($sockets[$i]) && $socket != $sockets[$i]; $i++) {
    }
    if (!isset($sockets[$i])) {
        $sockets[$sock_num] = $socket;
        $queues[$sock_num++] = "";
    }
    $recv = socket_read($socket, $config['max_len']);
    //$recv = str_replace($recv, "\r", "");
    if ($recv === "") {
        if (strpos($queues[$i], $config['line_ending']) === false) {
            return false;
        }
    } else {
        if ($recv !== false) {
            $queues[$i] .= $recv;
        }
    }
    $pos = strpos($queues[$i], $config['line_ending']);
    if ($pos === false) {
        return "";
    }
    $ret = substr($queues[$i], 0, $pos);
    $queues[$i] = substr($queues[$i], $pos + 1);
    return $ret;
}
Exemplo n.º 12
0
 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);
 }
Exemplo n.º 13
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.º 14
0
 /**
  * Method send
  *
  * @param string $raw_text
  *
  * @return string $return_text
  */
 public function send($raw_text)
 {
     if (!empty($raw_text)) {
         $this->raw_text = $raw_text;
         $xw = new xmlWriter();
         $xw->openMemory();
         $xw->startDocument('1.0');
         $xw->startElement('wordsegmentation');
         $xw->writeAttribute('version', '0.1');
         $xw->startElement('option');
         $xw->writeAttribute('showcategory', '1');
         $xw->endElement();
         $xw->startElement('authentication');
         $xw->writeAttribute('username', $this->username);
         $xw->writeAttribute('password', $this->password);
         $xw->endElement();
         $xw->startElement('text');
         $xw->writeRaw($this->raw_text);
         $xw->endElement();
         $xw->endElement();
         $message = iconv("utf-8", "big5", $xw->outputMemory(true));
         //send message to CKIP server
         set_time_limit(60);
         $protocol = getprotobyname("tcp");
         $socket = socket_create(AF_INET, SOCK_STREAM, $protocol);
         socket_connect($socket, $this->server_ip, $this->server_port);
         socket_write($socket, $message);
         $this->return_text = iconv("big5", "utf-8", socket_read($socket, strlen($message) * 3));
         socket_shutdown($socket);
         socket_close($socket);
     }
     return $this->return_text;
 }
Exemplo n.º 15
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.º 16
0
 private static function _tcp_send_request($socket_write_json = null)
 {
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if (false === $sock) {
         echo "sock create error!\n";
     }
     $address = Config::get("kgi.kgi_mid_server_ip");
     $port = Config::get("kgi.kgi_mid_server_port");
     try {
         $result = socket_connect($sock, $address, $port);
         if ($result === false) {
             echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($sock)) . "\n";
             exit;
             die;
         }
         socket_write($sock, $socket_write_json, strlen($socket_write_json));
         while ($out_str = socket_read($sock, 2048)) {
             //                echo "revice result\n";
             //                echo $out_str . "\n";
             $json_data = json_decode($out_str);
             break;
         }
         socket_close($sock);
     } catch (\ErrorException $e) {
         //echo $e->getMessage() . "\n";
     }
 }
Exemplo n.º 17
0
 function __construct($h, $p, $user, $pw)
 {
     // create server connection
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if (!socket_connect($this->socket, $h, $p)) {
         throw new Exception("Can't communicate with server.");
     }
     // receive timestamp
     $ts = $this->readString();
     // Hash container
     if (false !== strpos($ts, ':')) {
         // digest-auth
         $challenge = explode(':', $ts, 2);
         $md5 = hash("md5", hash("md5", $user . ':' . $challenge[0] . ':' . $pw) . $challenge[1]);
     } else {
         // Legacy: cram-md5
         $md5 = hash("md5", hash("md5", $pw) . $ts);
     }
     // send username and hashed password/timestamp
     socket_write($this->socket, $user . chr(0) . $md5 . chr(0));
     // receives success flag
     if (socket_read($this->socket, 1) != chr(0)) {
         throw new Exception("Access denied.");
     }
 }
Exemplo n.º 18
0
 /**
  * Read from the socket
  * 
  * @return string the information read from the socket
  *
  * @throws SocketException when the socket disconnects or the connection is lost
  */
 public function read()
 {
     if (false === ($buf = @socket_read($this->socket, 2048, PHP_NORMAL_READ))) {
         throw new SocketException();
     }
     return $buf;
 }
Exemplo n.º 19
0
 function query($query_string, $timeout)
 {
     $tmp = "";
     $string = "";
     $stime = array();
     $this->timer($stime);
     $n = strlen($query_string);
     if ($this->is_connected == 0) {
         $this->reconnect();
     }
     if ($this->sock && $n > 0 && socket_write($this->sock, $query_string, $n) == $n) {
         while (1) {
             if ($tmp = socket_read($this->sock, 81920, PHP_BINARY_READ)) {
                 if (($n = strpos($tmp, SOCK_END)) === FALSE) {
                     $string .= $tmp;
                 } else {
                     $string .= substr($tmp, 0, $n + strlen(SOCK_END));
                     break;
                 }
             } else {
                 $this->close();
                 return false;
             }
             $usec = $this->timer($stime);
             if ($usec >= $timeout) {
                 $this->close();
                 return false;
             }
             usleep(1);
         }
         return $string;
     }
     $this->close();
     return false;
 }
Exemplo n.º 20
0
 function Read()
 {
     if ($this->Connected) {
         return socket_read($this->Socket, 1024);
     }
     return null;
 }
Exemplo n.º 21
0
 /**
  * Send message package to the socket server
  * Basic layer method
  * 
  * @return mixed
  */
 public function send($msg, $is_block = false)
 {
     if (!$this->host || !$this->port) {
         throw new Hush_Socket_Exception("Please set server's host and port first");
     }
     /* Create a TCP/IP socket. */
     $this->sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($this->sock < 0) {
         echo "socket_create() failed.\nReason: " . socket_strerror($this->sock) . "\n";
     }
     $result = @socket_connect($this->sock, $this->host, $this->port);
     if ($result < 0) {
         echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n";
     }
     if ($is_block) {
         @socket_set_nonblock($this->sock);
     }
     // add suffix for socket msg
     $msg = trim($msg) . "\r\n";
     @socket_write($this->sock, $msg, strlen($msg));
     $result = @socket_read($this->sock, 2048);
     // unserialize data from socket server
     $result = unserialize(trim($result));
     return $result;
 }
Exemplo n.º 22
0
 function run_loop()
 {
     //This will stall the thread / request
     $i = 0;
     while ($_SESSION['running'] != -1) {
         #read from local socket and put on session variable
         while ($out = socket_read($this->socket, 8192)) {
             if ($out === false) {
                 exit("[Server] Unable to read from local socket");
             }
             $this->met_data .= $out;
         }
         #If data on SESSION variable write data to local socket
         if ($this->handler_data != "") {
             $in = socket_write($this->socket, $this->handler_data, strlen($this->handler_data));
             if ($in === false) {
                 exit("[Server] Unable to write to local socket");
             }
             $this->handler_data = "";
         }
         $this->update_session_data();
         if (!stristr(PHP_OS, "linux")) {
             sleep(1);
         }
         //added to work with apache/IIS on windows otherwise the consecutive reads DoS the socket
     }
 }
Exemplo n.º 23
0
function queryAPI($jsonQuery)
{
    $service_port = 12345;
    $address = "localhost";
    $msg = "{\n   \"array\": [\n";
    echo $msg;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        die('{"type" : "error", "msg" : "connection error: ' . socket_strerror(socket_last_error()) . '"}]}');
    }
    $result = socket_connect($socket, $address, $service_port);
    if ($result === false) {
        die('{"type" : "error", "msg" : "connection error: ' . socket_strerror(socket_last_error($socket)) . '"}]}');
    }
    $in = stripslashes($jsonQuery);
    socket_write($socket, $in, strlen($in));
    socket_write($socket, ';', 1);
    $buffer = "";
    while ($out = socket_read($socket, 2048)) {
        echo $out;
        ob_flush();
        flush();
    }
    #JSON Array end
    $msg = "]\n }";
    echo $msg;
    echo PHP_EOL;
    ob_flush();
    flush();
    socket_close($socket);
}
Exemplo n.º 24
0
function hg_sendCmd($cmd, $ip, $port)
{
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket < 0) {
        return false;
    }
    $result = socket_connect($socket, $ip, $port);
    if ($result < 0) {
        return false;
    }
    if (!isset($cmd['charset'])) {
        $cmd['charset'] = '';
    }
    $str = json_encode($cmd);
    //echo ($str);
    //$str = base64_encode($str);
    socket_write($socket, $str, strlen($str));
    $data = '';
    while ($out = socket_read($socket, 256)) {
        $data .= $out;
        if (strlen($out) < 256) {
            break;
        }
    }
    socket_close($socket);
    //$data = base64_decode($data);
    return $data;
}
Exemplo n.º 25
0
 /**
  * ソケット待ち受け処理
  */
 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);
     }
 }
Exemplo n.º 26
0
function sendsock($in)
{
    global $config;
    $service_port = $config['sockport'];
    $address = $config['sockhost'];
    if (!function_exists("socket_create")) {
        error_log(date("y-m-d H:i:s") . " 未启用socket模块\n", 3, "error.log");
        return null;
    }
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        error_log(date("y-m-d H:i:s") . "socket_create() failed, reason: " . socket_strerror(socket_last_error()) . "\n", 3, "error.log");
        return null;
    }
    $result = socket_connect($socket, $address, $service_port);
    if ($result === false) {
        error_log(date("y-m-d H:i:s") . "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($socket)) . "\n", 3, "error.log");
        return null;
    }
    socket_write($socket, $in, strlen($in));
    $result = socket_read($socket, 8192);
    $arr = unpack("C*", $result);
    socket_close($socket);
    return $arr;
}
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 function read($length = 1024)
 {
     $data = '';
     while (true) {
         $read = array($this->socket);
         $write = array();
         $except = array();
         $r = socket_select($read, $write, $except, 0, self::TIMEOUT_USEC);
         if (false === $r) {
             throw new PhpBuf_RPC_Socket_Exception('socket select fail: ' . socket_strerror(socket_last_error()));
         }
         if (0 === $r) {
             continue;
         }
         $result = @socket_read($this->socket, $length, PHP_BINARY_READ);
         if (false === $result) {
             throw new PhpBuf_RPC_Socket_Exception('read error:' . socket_strerror(socket_last_error()));
         }
         if (empty($result)) {
             break;
         }
         $data .= $result;
     }
     return $data;
 }
Exemplo n.º 29
0
 public function index()
 {
     error_reporting(E_ALL);
     set_time_limit(0);
     $service_port = 6005;
     $address = "203.130.45.233";
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($socket < 0) {
         echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
     }
     $result = socket_connect($socket, $address, $service_port);
     if ($result < 0) {
         echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n";
     } else {
         echo "连接OK<br>";
     }
     $in = "1!";
     //1!是发给这个设备的指令
     $out = '';
     $out1 = '';
     if (!socket_write($socket, $in, strlen($in))) {
         echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
     }
     while ($out = socket_read($socket, 8192)) {
         //$out=trim($out,"0xff");
         //$out=trim($out,"0x00");
         //$this->xieru($out,"sj");
         echo $out;
     }
     socket_close($socket);
 }
Exemplo n.º 30
-1
function sendUSD($text, $pass_server = '000000')
{
    $address = gethostbyname('127.0.0.1');
    //IP Адрес вашего компьютера
    $service_port = 8000;
    //Порт
    //$pass_server='000000'; //Пароль
    $phone = preg_replace('/^\\+/', '', $phone);
    $socket = socket_create(AF_INET, SOCK_STREAM, 0);
    if ($socket < 0) {
        echo "socket create failed reason: " . socket_strerror($socket) . "\n";
    }
    $result = socket_connect($socket, $address, $service_port);
    if ($result < 0) {
        echo "socket connect failed.\nReason: ({$result}) " . socket_strerror($result) . "\n";
    }
    $text = iconv("UTF-8", "Windows-1251", $text);
    $in = base64_encode($pass_server . "#CMD#[USSD]" . $text);
    //Пример отправки смс
    //$in = base64_encode($pass_server."#CMD#[USSD]*102#"); //Пример запроса USSD команды
    $out = '';
    socket_write($socket, $in, strlen($in));
    //echo "Response:\n\n";
    $res = '';
    while ($out = socket_read($socket, 2048)) {
        $res .= $out;
    }
    socket_close($socket);
    $res = iconv("Windows-1251", "UTF-8", $res);
    if (preg_match('/USSD-RESPONSE\\[.+?\\]:(.+)/is', $res, $m)) {
        $res = $m[1];
    }
    return $res;
}