欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php实现与python进行socket通信的方法示例

程序员文章站 2022-03-12 19:38:51
本文实例讲述了php实现与python进行socket通信的方法。分享给大家供大家参考,具体如下: 设计目的 通过前端页面发起请求交给php,php创建socket请求...

本文实例讲述了php实现与python进行socket通信的方法。分享给大家供大家参考,具体如下:

设计目的

通过前端页面发起请求交给php,php创建socket请求交给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('mysocket.php');
$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 = '192.168.238.1';
      $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;
      }
    }
  }
}
?>

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相关内容感兴趣的读者可查看本站专题:《php socket用法总结》、《php字符串(string)用法总结》、《php数学运算技巧总结》、《php面向对象程序设计入门教程》、《php数组(array)操作技巧大全》、《php数据结构与算法教程》、《php程序设计算法总结》及《php网络编程技巧总结

希望本文所述对大家php程序设计有所帮助。