>  기사  >  백엔드 개발  >  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;
      }
    }
  }
}
?>

멀티 서버 .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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.