如何在循环中打破这个PHP?

时间:2016-10-01 23:45:31

标签: php while-loop bots irc

我是PHP的新手,并且正在使用加入频道,发送消息然后退出的IRC机器人。

除了发送$ message之后,所有内容都在脚本中工作(第6行),我不明白如何退出无限循环。

// Open Internet connection
$socket = fsockopen("$server", $port);
fputs($socket,"USER $nick $nick $nick $nick :$nick\n");
fputs($socket,"NICK $nick\n");
fputs($socket,"JOIN ".$chan."\n");
fputs($socket, "PRIVMSG ".$chan." :$message1\n");


// Begin while loop
while(1) {
    while($data = fgets($socket)) {
        echo nl2br($data);
        flush();

        $ex = explode(' ', $data);
        $channel = $ex[2];
        $nicka = explode('@', $ex[0]);
        $nickb = explode('!', $nicka[0]);
        $nickc = explode(':', $nickb[0]);

        // $host = $nicka[1];
        $nick = $nickc[1];
        if($ex == "PING"){
            fputs($socket, "PONG ".$ex[1]."\n");
        }

        $args = NULL; for ($i = 4; $i < count($ex); $i++) { $args .= $ex[$i] . ' '; }

    }
}

2 个答案:

答案 0 :(得分:1)

你需要只有1个while循环,它会在条件为真时停止。

您可以阅读http://php.net/manual/en/control-structures.while.php

while(1) {     // <-- Remove the infinite loop 
    while($data = fgets($socket)) {

答案 1 :(得分:0)

如果你必须打开插座,你需要一段时间。解决此问题的最佳方法是使用回调。但如果你只想打破局面。

// Open Internet connection
$socket = fsockopen("$server", $port);
fputs($socket,"USER $nick $nick $nick $nick :$nick\n");
fputs($socket,"NICK $nick\n");
fputs($socket,"JOIN ".$chan."\n");
fputs($socket, "PRIVMSG ".$chan." :$message1\n");


// Begin while loop
all_data_received = False
while(1) {
while($data = fgets($socket)) {
    echo nl2br($data);
    flush();

    $ex = explode(' ', $data);
    $channel = $ex[2];
    $nicka = explode('@', $ex[0]);
    $nickb = explode('!', $nicka[0]);
    $nickc = explode(':', $nickb[0]);

    // $host = $nicka[1];
    $nick = $nickc[1];
    if($ex == "PING"){
        fputs($socket, "PONG ".$ex[1]."\n");
    }

    $args = NULL; for ($i = 4; $i < count($ex); $i++) { $args .= $ex[$i] . ' '; 

    all_data_received = True //or some other conditions 

    }

    if (all_data_received == True){
        break;
        }

}