duanmorong9597 2011-09-12 16:06 采纳率: 100%
浏览 61
已采纳

php socket_accept陷入僵局

Hello i made a php socket server to get data from plc, plc is configured as tcp socket client. I've a seriuous problem, if local net go down seems that function socket_accept stalled, plc don'be able to send me data. If i restart my server plc reconnect correctly.

Can someone hel me? My server code:

error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = ipserver;
$port = 10001;    

if (($sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname("TCP"))) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "
";
    exit;
}

if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error($sock));
    exit;
} 

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "
";
    exit;
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "
";
    exit;
}

     while(true)
{
    //$remote_fd = socket_accept($sock);
    if (($remote_fd = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "
";
        break ;
    }
    do {
        $recv = "";
        if (false === ($recv = socket_read($remote_fd, 128, PHP_BINARY_READ))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($remote_fd)) . "
";
            #break 2;
        }
        if($recv != "") {
            echo $recv."
";
            inserisci_letture("t_letture",trim($recv));
            if($sent=socket_write($remote_fd,"1",1)===false)
            {
                echo "socket_write() failed: reason: " . socket_strerror(socket_last_error($remote_fd)) . "
";
            }
        }
    } 
    while($recv != ""); 
}
socket_shutdown($sock);
socket_close($sock);


?>
  • 写回答

1条回答 默认 最新

  • doumengyin0491 2011-09-12 19:42
    关注

    Listen on 0.0.0.0 instead of a specific interface, so that the socket is not closed if the network (the interface) does down. This is a special address that listens on all interfaces.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Android STD快速启动
  • ¥15 如何使用simulink建立一个永磁同步直线电机模型?
  • ¥30 天体光谱图的的绘制并得到星表
  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动