简体   繁体   English

我怎样才能打破这个 PHP while 循环?

[英]How can I break this PHP while loop?

I'm new to PHP and working on an IRC bot that joins a channel, sends a message, and then exits.我是 PHP 新手,正在开发一个加入频道、发送消息然后退出的 IRC 机器人。

Everything is working in the script except after $message is sent (line 6), I don't understand how to exit the infinite loop.除了发送 $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] . ' '; }

    }
}

You need to only have 1 while loop that will stop when a condition is true.您只需要 1 个 while 循环,当条件为真时就会停止。

You can read http://php.net/manual/en/control-structures.while.php你可以阅读http://php.net/manual/en/control-structures.while.php

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

If you have to leave the socket open you need the while.如果您必须让套接字保持打开状态,则需要一段时间。 The best way to resolve this is with a callback.解决此问题的最佳方法是使用回调。 But if you only want to break the whiles.但如果你只想打破时间。

// 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;
        }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM