PHP 소켓 네트워크 작업 클래스의 정의 및 사용법을 설명하는 예

巴扎黑
풀어 주다: 2023-03-15 17:26:01
원래의
1445명이 탐색했습니다.

이 글에서는 PHP 소켓 네트워크 연산 클래스의 정의와 사용법을 주로 소개하고, 필요한 친구와 조합하여 쿼리 요청을 보내는 등 관련 사용법과 PHP 소켓 네트워크 연산 클래스의 정의를 분석합니다. 참고하시면 됩니다

이 글에서는 PHP 소켓 네트워크 연산 클래스의 정의와 사용법에 대한 예제를 설명하고 있습니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.

웹 프론트 엔드 테스트:


<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 = &#39;192.168.238.1&#39;;
      $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(&#39;mysocket.php&#39;);
$con = Connector::getInstance();
$req = $_GET[&#39;cmd&#39;];
$con->sendMsg($req);
$ret = $con->getMsg();
echo $ret;
?>
로그인 후 복사

응용 프로그램 설명:

클라이언트는 Php를 호출하기 위한 ajax 요청을 시작하고 PHP는 소켓의 도움으로 C++ 모듈에 대한 요청을 추가로 시작합니다.

위 내용은 PHP 소켓 네트워크 작업 클래스의 정의 및 사용법을 설명하는 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!