本php小白想在前端打开和关闭php写的tcp服务器,可是可以打开到socket在listening,希望在没有客户端连接和不需要时关闭socket,求助!!!上代码
前端:
<button id="opentcp">连接</button> <button id="closetcp">关闭</button> <script type="text/javascript"> $(document).ready(function(){ $("#opentcp").click(function(){ $.ajax({ type: "GET", url: "test.php" }); }); $("#closetcp").click(function(){ $.ajax({ type: "POST", url: "test.php" }); }); }) </script>
php:
<?php $sock; if ($_SERVER["REQUEST_METHOD"] == "GET") { server(); } if ($_SERVER["REQUEST_METHOD"] == "POST") { socket_close($sock); } function server(){ set_time_limit(0); $ip = '127.0.0.1'; $port = 1935; do { global $sock; $sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); $ret = socket_bind($sock,$ip,$port); $ret = socket_listen($sock,4); $msgsock = socket_accept($sock); socket_close($msgsock); socket_close($sock); } while (true); }