欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-12 19:14:38
本文实例讲述了php socket网络操作类定义与用法。分享给大家供大家参考,具体如下: web前端测试: ...

本文实例讲述了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字符串(string)用法总结》、《php数学运算技巧总结》、《php面向对象程序设计入门教程》、《php数组(array)操作技巧大全》、《php数据结构与算法教程》、《php程序设计算法总结》及《php网络编程技巧总结

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