• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

实例讲解PHP Socket网络操作类定义与用法

php 搞代码 3年前 (2022-01-22) 14次浏览 已收录 0个评论

这篇文章主要介绍了PHP Socket网络操作类定义与用法,结合实例形式分析了php socket网络操作类的定义及结合ajax发送查询请求等相关使用技巧,需要的朋友可以参考下

本文实例讲述了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:

<?phpclass 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 a<p>+本文来源gao!%daima.com搞$代*!码9网(</p><strong>搞gaodaima代码</strong>s $read_sock)      {        $data = @socket_read($read_sock,1024,PHP_BINARY_READ);        socket_close($this->conn);        return $data;      }    }  }}?>

main.php(调用场所):

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

应用说明:

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

以上就是实例讲解PHP Socket网络操作类定义与用法的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:实例讲解PHP Socket网络操作类定义与用法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址