gpt4 book ai didi

php - 连接后保持 PHP 服务器套接字处于事件状态

转载 作者:行者123 更新时间:2023-12-03 11:50:12 26 4
gpt4 key购买 nike

我有一个服务器套接字页面,它基本上接收一个字符串,将其反转并将其发送回客户端,效果很好,但是套接字在连接后关闭,尝试修复此问题但无济于事,谁能告诉我我是什么我做错了吗?

    $host = "192.168.8.121";
$port = 232;

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


$input = trim($input);
echo "Client Message : ".$input;

// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");

// close sockets
socket_close($spawn);
socket_close($socket);

最佳答案

您需要一个套接字读取循环:

function error($socket) {
return socket_strerror(socket_last_error($socket));
}

$host = "127.0.0.1";
$port = 1024;

set_time_limit(0);

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or
die(__LINE__ . ' => ' . error($socket));

$result = socket_bind($socket, $host, $port) or
die(__LINE__ . ' => ' . error($socket));

$result = socket_listen($socket, 3) or
die(__LINE__ . ' => ' . error($socket));

$spawn = socket_accept($socket) or
die(__LINE__ . ' => ' . error($socket));

while(true) {

$input = socket_read($spawn, 1024) or
die(__LINE__ . ' => ' . error($socket));

$input = trim($input);

if ($input == 'exit') {
echo 'exiting from server socket read loop';
break;
}

echo "Client Message : " . $input . '<br>';

// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen($output)) or
die(__LINE__ . ' => ' . error($socket));

}

// close sockets
socket_close($spawn);
socket_close($socket);

关于php - 连接后保持 PHP 服务器套接字处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47052139/

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