PHP和python之间的socket通信示例

来源:爱站网时间:2020-08-06编辑:网友分享
程序的开发需要我们不断的进行学习,然后才能把学到的知识运用到我们需要的项目中,让这个项目变得活灵活现的,本文为大家带来了PHP和python之间的socket通信示例,相信对大家学习这方面的知识有一点的帮助。

程序的开发需要我们不断的进行学习,然后才能把学到的知识运用到我们需要的项目中,让这个项目变得活灵活现的,本文为大家带来了PHP和python之间的socket通信示例,相信对大家学习这方面的知识有一点的帮助。

设计目的

通过前端页面发起请求交给php,php创建socket请求交给Python脚本,然后执行完毕之后,返回给前端。

index.html


test



service / main.php

sendMsg($req);
$ret = $con->getMsg();
echo $ret;
?>

service / mysocket.php

conn = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) conn)."\n";
      }
      $result = socket_connect($this->conn, $ip, $port);
      if ($result conn,$msg);
  }
  public function getMsg()
  {
    $clients = array($this->conn);
    while(true)
    {
      $read = $clients;
      $wrSet = NULL;
      $errSet = NULL;
      if(socket_select($read, $wrSet,$errSet, 3) conn);
        return $data;
      }
    }
  }
}
?>

multiServer.py

import threading
import socket
import time
encoding = 'utf-8'
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 = ' '
    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之间的socket通信示例,其实我们程序员也要付出努力才能让有所成就,而我们的项目想要变得与众不同,这和我们程序员积累的知识是成正比的哦。

上一篇:在phpstudy中配置多站点、多端口的详细步骤

下一篇:详细说明如何利用PHPStorm开发Laravel应用

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载