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

yipeiwu_com5年前PHP代码库

本文实例讲述了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程序设计有所帮助。

相关文章

php中0,null,empty,空,false,字符串关系的详细介绍

在一个项目中遇到了一个奇怪的问题,耗费了我不少时间都没有解决,最终调试发现是判断的问题—-关于0和 ‘ ‘ (空单引号,为好看清我加了个空格)的判断,我发现 0==” 居然成立,郁闷的同...

php简单浏览目录内容的实现代码

如下所示:复制代码 代码如下:<?php$dir = dirname(__FILE__);$open_dir = opendir($dir);echo "<table bor...

详解WordPress中用于更新和获取用户选项数据的PHP函数

update_user_option()函数 update_user_option()函数作用利用全局博客权限更新用户选项。 用户选项类似于用户元数据,唯一的不同之处在于用户选项支持全局...

smarty实现多级分类的方法

smarty实现多级分类的方法

本文实例讲述了smarty实现多级分类的方法。分享给大家供大家参考。具体分析如下: 这里简单的介绍一下利用php smarty 多级分类读出与循环方法,单循环很简单,但是多级就要复杂一点...

php 中文字符入库或显示乱码问题的解决方法

大家以后在编写过程中, 一定要记得定义字符类型。mysql_query("set names 'gbk'") 解决的方法就这么简单。 今天做了一个数据库查询,放出代码。 复制代码 代码如...