PHP Socket Client 只发送和接收一条消息

Posted

技术标签:

【中文标题】PHP Socket Client 只发送和接收一条消息【英文标题】:PHP Socket Client only sends and receives one message 【发布时间】:2019-11-08 02:18:04 【问题描述】:

我最近开始学习php socket。 我想在服务器和客户端之间创建一个永久 TCP 连接!但是我的 。我想通过一个连接无限期地发送和接收消息。

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

?>

客户端.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);
?>

【问题讨论】:

【参考方案1】:

在server.php中,你需要在socket_accept之后的代码再添加一个while(trur) ,因为如果你每次运行socket_accept,最后建立的连接将不再起作用。

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

【讨论】:

以上是关于PHP Socket Client 只发送和接收一条消息的主要内容,如果未能解决你的问题,请参考以下文章

Socket通信案例--实现发送与接收数据

websocket client怎样维持心跳,有没有具体的栗子

ObjectOutput/InputStream 只发送和接收一次对象

UDP Client 和 Socket 的区别

Node.js 到 C++ 客户端:未从 socket.emit 接收消息

细说websocket - php篇