gpt4 book ai didi

php - 如何在第一次连接后保持 php web 套接字连接打开

转载 作者:行者123 更新时间:2023-12-02 08:35:31 24 4
gpt4 key购买 nike

我在尝试学习套接字时使用以下代码作为套接字的服务器,但客户端代码只能工作一次,每次运行 clint 代码之前我都必须运行服务器脚本。

那么我什么时候运行此 server.php 以继续监听客户端请求?

服务器.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);
}

关于php - 如何在第一次连接后保持 php web 套接字连接打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21996694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com