簡體   English   中英

第一次連接后如何保持php Web套接字連接打開

[英]How to keep a php web socket connection open after first connection

在嘗試學習套接字時,我將以下代碼用作套接字的服務器,但是客戶端代碼只能運行一次,每次運行clint代碼之前,我都必須運行服務器腳本。

因此,何時運行此server.php以繼續偵聽客戶端請求?

SERVER.PHP

$host = "127.0.0.1";
$port = 25003;
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
$input = socket_read($spawn, 1024) or die("Could not read input\n");
if ($input == "Hey"){
    $input = "Hey you don't shout me. Talk properly...";
    } else if ($input == "Vetra"){
        $input = "Hello how are you there, whats your name?";
        } else { $input = "Well, what can i say, you must be a human being.";
}
echo $input;
$output = $input . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
//socket_close($spawn);
//socket_close($socket);

客戶端PHP

$host    = "127.0.0.1";
$port    = 25003;
$message = $_POST['data'];
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo $result;
//socket_close($socket);

您應該等待無限循環中的新連接:

$host = "127.0.0.1";
$port = 25003;
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
while(true) {
  $spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
  $input = socket_read($spawn, 1024) or die("Could not read input\n");
  if ($input == "Hey"){
    $input = "Hey you don't shout me. Talk properly...";
  } else if ($input == "Vetra"){
    $input = "Hello how are you there, whats your name?";
  } else {
    $input = "Well, what can i say, you must be a human being.";
  }
  echo $input.PHP_EOL;
  $output = $input . "\n";
  socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
  socket_close($spawn);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM