PHP Socket network operation class definition and usage example, socket example
This example describes the definition and usage of PHP Socket network operations. We will share this with you for your reference. The details are as follows:
Web Front-end testing:
<Html>
Mysocket. php:
<? Phpclass Connector {public static $ instance = null; public $ conn; private function _ construct () {set_time_limit (0); $ ip = '2017. 168.238.1 '; $ port = 8888; if ($ this-> conn = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) <0) {echo "socket_create () failure is caused: ". 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 "connection 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 (call place ):
<?phprequire_once('mysocket.php');$con = Connector::getInstance();$req = $_GET['cmd'];$con->sendMsg($req);$ret = $con->getMsg();echo $ret;?>
Application description:
The client ajax initiates a request to call Php, and then php uses socket to further initiate a request to the C ++ module.