温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在PHP中定义一个Socket网络操作类

发布时间:2021-04-15 16:14:14 来源:亿速云 阅读:164 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关怎么在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;
?>

关于怎么在PHP中定义一个Socket网络操作类就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI