PHP Socket network operation class definition and usage example, socket example

Source: Internet
Author: User
Tags sendmsg

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.