Implementing long-polling with jQuery and PHP

后端 未结 2 1708
误落风尘
误落风尘 2021-01-03 06:49

I want to build a chat, based on JavaScript (jQuery will be used for AJAX) and PHP.

I\'ve heard a good way of doing this is to use long-polling.

I do underst

2条回答
  •  自闭症患者
    2021-01-03 07:04

    You don't want to create an infinite loop, but you can set a timeout. Basically loop for X second waiting for some sort of data, and if that doesn't happen send a response to the client telling it that it needs to initiate a new request, which will have the same timeout period.

    $source; // some data source - db, etc
    $data = null; // our return data
    $timeout = 30; // timeout in seconds
    $now = time(); // start time
    
    // loop for $timeout seconds from $now until we get $data
    while((time() - $now) < $timeout) {
        // fetch $data
        $data = $source->getData();
    
        // if we got $data, break the loop
        if (!empty($data)) break;
    
        // wait 1 sec to check for new $data
        usleep(10000);
    }
    
    // if there is no $data, tell the client to re-request (arbitrary status message)
    if (empty($data)) $data = array('status'=>'no-data');
    
    // send $data response to client
    echo json_encode($data);
    

提交回复
热议问题