我最近开始学习php套接字。 我想在服务器和客户端之间创建一个永久的TCP连接!但是我的PHP Socket Client只发送和接收一条消息。我想通过一个连接无限期地发送和接收消息。
Server.php:
<?php
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, '127.0.0.1', '8088') 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, 2048) or die("Could not read input\n");
echo base64_encode($input)."\r\n";
$output="OK";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
//socket_close($spawn);
//socket_close($socket);
}
?>
Client.php:
<?php
set_time_limit(0);
$input="Hi";
$socket2 = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result2 = socket_connect($socket2, '127.0.0.1', '8088') or die("Could not connect to server\n");
while(true) {
socket_write($socket2, $input, strlen($input)) or die("Could not send data to server\n");
$result2 = socket_read ($socket2, 2048) or die("Could not read server response\n");
$output=$result2;
echo $output;
sleep(2);
}
//socket_close($spawn);
//socket_close($socket);
?>
答案 0 :(得分:0)
在server.php中,您需要在while(trur) {}
之后为代码添加另一个socket_accept
,因为如果您每次运行socket_accept
,最后建立的连接将不再起作用。 / p>
<?php
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, '127.0.0.1', '8088') 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");
while(true) {
$input = socket_read($spawn, 2048) or die("Could not read input\n");
echo base64_encode($input)."\r\n";
$output="OK";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
}
}
//socket_close($spawn);
//socket_close($socket);