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

前端之家收集整理的这篇文章主要介绍了php实现与python进行socket通信的方法示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

设计目的

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

index.html

test

service / main.PHP

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

service / mysocket.PHP

PHP;"> 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

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程序设计有所帮助。

原文链接:https://www.f2er.com/php/16858.html

猜你在找的PHP相关文章