ホームページ  >  記事  >  バックエンド開発  >  phpとpython間のソケット通信の実装例

phpとpython間のソケット通信の実装例

巴扎黑
巴扎黑オリジナル
2017-09-01 16:34:421877ブラウズ

この記事では、主にphpとpythonの間のソケット通信の方法を紹介し、カスタムクラスを使用してソケットリクエストデータを送信するphpと、ソケットデータを受信して​​リクエストを処理するPythonなど、関連する操作スキルをサンプルの形で分析します。参考にしてください

この記事の例では、phpとpythonの間でソケット通信を実装する方法を説明します。参考までに皆さんと共有してください。詳細は次のとおりです:

設計の目的

フロントエンドページを通じてリクエストを開始し、それをphpに渡します。PHPはソケットリクエストを作成し、それをphpに渡します。 Python スクリプトを実行し、実行が完了するとフロントエンドに戻ります。

index.html


<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()
  {
    g_xmlHttpReq.open("GET","./service/main.php?cmd=1",true);
    g_xmlHttpReq.onreadystatechange=onReplyCallback;
    g_xmlHttpReq.send(null);
  }
  </script>
</head>
<body>
<button onclick="on_stop_service()">关闭服务</button>
</body>
</html>

service/main.php


<?php
require_once(&#39;mysocket.php&#39;);
$con = Connector::getInstance();
$req = "aaaaaaa";
$con->sendMsg($req);
$ret = $con->getMsg();
echo $ret;
?>

service/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;
      }
    }
  }
}
?>

multi Server.py


import threading
import socket
import time
encoding = &#39;utf-8&#39;
BUFSIZE = 1024
# a read thread, read data from remote
class 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(data):
       string = bytes.decode(data, encoding)
       print "from client::",string,""
       time.sleep(10)
       self.client.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 = &#39; &#39;
    else:
      string = False
    return string
# a listen thread, listen remote connect
# when a remote machine request to connect, it will create a read thread to handle
class 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 thread
lst.start() # then start
# Now, you can use telnet to test it, the command is "telnet 127.0.0.1 9011"
# You also can use web broswer to test, input the address of "http://127.0.0.1:9011" and press Enter button
# Enjoy it....

以上がphpとpython間のソケット通信の実装例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。