socket(php)(不确定是否是长连接)(一次连接,多次接受,发送特定字符时关闭连接)整理版本3

来源:互联网 发布:8080端口如何开启 编辑:程序博客网 时间:2024/06/05 15:52
<?php  set_time_limit(0);  $ip = '192.168.1.52';  $port = 8079;    /*----------------    以下操作都是手册上的    -------------------*/  if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {      echo "socket_create() 失败的原因是:".socket_strerror($sock)."\n";  }   if(($ret = socket_bind($sock,$ip,$port)) < 0) {      echo "socket_bind() 失败的原因是:".socket_strerror($ret)."\n";  }   if(($ret = socket_listen($sock,4)) < 0) {      echo "socket_listen() 失败的原因是:".socket_strerror($ret)."\n";  }    $count = 0;      do {      if (($msgsock = socket_accept($sock)) < 0) {          echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";          break;      } else {                    $msg = "\nPHP Test Server. \n" ."用quit,shutdown,sun...等命令测试.\n";          socket_write($msgsock, $msg, strlen($msg));         socket_last_error();           do{        if(false ===($buf = socket_read($msgsock,8192))){        echo "socket_read() failed: reason: " . socket_strerror($ret) . "\n";                  break 2;         }         if (!$buf = trim($buf)) {                  continue;          }          if ($buf == 'quit') {                  break;          }          if ($buf == 'shutdown') {                  socket_close($msgsock);                  break 2;          }          if ($buf == 'sun') {                  echo'what are you doing?';          }                             $talkback = "收到的信息:" . $buf;          socket_write($msgsock, $talkback, strlen($talkback));        echo $talkback . '<br /n>';        }while(true);                             }      socket_close($msgsock);      } while (true);      socket_close($sock);    ?>

原创粉丝点击