PHP Socket网络操作类定义与用法示例

秋天,大雁南飞,草木枯荣,掉落下的依依不舍的树叶随着瑟瑟的秋风飞动。尽管田园一片荒凉,但金灿灿的干草已覆盖了整个大地,几颗松树笔直的立在大地上,天空是多么广阔,多么蔚蓝!地是多么浩瀚,多么无边!天和地连在了一起,已分不清地平线在哪里,秋天的原野拥抱着蓝天,广阔的蓝天拥抱着田野!

本文实例讲述了PHP Socket网络操作类定义与用法。分享给大家供大家参考,具体如下:

web前端测试:

<html>
<head>
  <title>test</title>
  <script>
  g_xmlHttpReq = new XMLHttpRequest();
  function onReplyCallback()
  {
    if(g_xmlHttpReq.readyState==4 && g_xmlHttpReq.status==200)
    {
      alert(g_xmlHttpReq.responseText);
    }
  }
  function on_stop_service()
  {
    var cmd = document.getElementById("inCmd").value;
    g_xmlHttpReq.open("GET","./service/main.php?cmd=" + cmd,true);
    g_xmlHttpReq.onreadystatechange=onReplyCallback;
    g_xmlHttpReq.send(null);
  }
  </script>
</head>
<body>
<input type="text" id="inCmd">
<hr>
<button onclick="on_stop_service()">关闭服务</button>
</body>
</html>

mysocket.php:

<?php
class Connector
{
  public static $instance=null;
  public $conn;
  private function __construct()
  {
      set_time_limit(0);
      $ip = '192.168.238.1';
      $port = 8888;
      if(($this->conn = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0)
      {
        echo "socket_create() 失败的原因是:".socket_strerror($this->conn)."\n";
      }
      $result = socket_connect($this->conn, $ip, $port);
      if ($result < 0) {
        echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
      }else {
        echo "连接OK\n";
      }
  }
  public static function getInstance()
  {
    if(is_null(self::$instance))
    {
      self::$instance = new Connector;
    }
    return self::$instance;
  }
  public function sendMsg($msg)
  {
    socket_write($this->conn,$msg);
  }
  public function getMsg()
  {
    $clients = array($this->conn);
    while(true)
    {
      $read = $clients;
      $wrSet = NULL;
      $errSet = NULL;
      if(socket_select($read, $wrSet,$errSet, 3) < 1)
      {
        continue;
      }
      foreach($read as $read_sock)
      {
        $data = @socket_read($read_sock,1024,PHP_BINARY_READ);
        socket_close($this->conn);
        return $data;
      }
    }
  }
}
?>

main.php(调用场所):

<?php
require_once('mysocket.php');
$con = Connector::getInstance();
$req = $_GET['cmd'];
$con->sendMsg($req);
$ret = $con->getMsg();
echo $ret;
?>

应用说明:

客户端ajax发起请求调用Php,然后php借助socket进一步发起请求给C++模块。

希望本文所述对大家PHP程序设计有所帮助。

以上就是PHP Socket网络操作类定义与用法示例。一开始,年轻人喜欢晦涩书籍深刻电影,是因为人生过于浅薄,需要填充物。等到稍微成长一点,就懂得了老人们为什么喜欢日出而作日落而息粗茶淡饭笑看一切繁杂,因为,人生翻来覆去反正就那么点事,不用装,谁都不深刻。更多关于PHP Socket网络操作类定义与用法示例请关注haodaima.com其它相关文章!

标签: PHP Socket