Example of how to implement socket communication between PHP and Python

Source: Internet
Author: User
This article mainly introduces the PHP implementation of the socket communication with Python method, combined with an example of PHP to use the custom class to send socket request data and Python to receive socket data and processing requests and other related operations skills, the need for friends can refer to the next

The example in this paper describes how PHP implements socket communication with Python. Share to everyone for your reference, as follows:

Design Purpose

Send a request to php,php to create a socket request to the Python script via the front-end page, and then return to the front end after execution is complete.

Index.html



service/main.php


<?phprequire_once (' mysocket.php '); $con = Connector::getinstance (); $req = "Aaaaaaa"; $con->sendmsg ($req); $ret = $con->getmsg (); Echo $ret;? >

service/mysocket.php


<?phpclass 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 () failed due to:". SOCK Et_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; }}}}?>

multiserver.py


Import threadingimport Socketimport timeencoding = ' utf-8 ' BUFSIZE = 1024# A read thread, read data from Remoteclass Reader (Threading. Thread): Def __init__ (self, client): Threading. Thread.__init__ (self) self.client = client def run (self): #while true:data = SELF.CLIENT.RECV (BUFSIZE) if (da TA): string = Bytes.decode (data, encoding) print "From client::", String, "" Time.sleep (Ten) Self.cli Ent.send ("Return Frome Server::" + string) print "Close:", Self.client.getpeername () def readline (self): rec = self . Inputs.readline () If rec:string = Bytes.decode (REC, encoding) if Len (string) >2:string = String[0  : -2] else:string = "else:string = False return string# A listen thread, listen remote connect# When a remote machine request to connect, it would create a read thread to Handleclass Listener (threading. Thread): Def __init__ (self, port): Threading. Thread.__init__ (self) self.port = Port Self.sOck = Socket.socket (socket.af_inet, socket. SOCK_STREAM) self.sock.setsockopt (socket. Sol_socket, SOCKET.    SO_REUSEADDR, 1) self.sock.bind (("0.0.0.0", Port)) Self.sock.listen (0) def run (self): print "Listener started"      While true:client, Cltadd = self.sock.accept () print "Accept a connect ..." Reader (client). Start () Cltadd = Cltadd print "Accept a connect (new reader ...)"  LST = Listener (8888) # Create a Listen Threadlst.start () # Then start# now, you can use Telnet to test it, the command is "Telnet 127.0.0.1 9011" # also can use web broswer to test, input the address of "http://127.0.0.1:9011" and press Ent Er button# Enjoy it ....

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.