PHP 第二節 數據類型之數組
758
2023-12-09
本文實例講述了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 "連接OKn"; } } 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程序設計有所幫助。
#免責聲明#
本站[綠夏技術導航]提供的一切軟件、教程和內容信息僅限用于學習和研究目的;不得將上述內容用于商業或者非法用途,否則,一切后果請用戶自負。本站信息來自網絡收集整理,版權爭議與本站無關。您必須在下載后的24個小時之內,從您的電腦或手機中徹底刪除上述內容。如果您喜歡該程序或內容,請支持正版,購買注冊,得到更好的正版服務。我們非常重視版權問題,如有侵權請郵件[admin@lxwl520.com]與我們聯系進行刪除處理。敬請諒解!