2016-11-13 1 views
0

나는 https://github.com/ghedipunk/PHP-Websockets PHP 클래스를 사용하여 대화를 작성하려고합니다. 이제 클라이언트 쪽에서 시작 JS에서 서버에 연결 한 다음 3 초에 한 번 요청을 보내고 모든 요청에 ​​서버가 데이터베이스의 메시지를 확인하고 클라이언트에 메시지를 보내는 것처럼 보입니다. 클라이언트가 3 초에 한 번 요청을 보내고 데이터베이스에 새 메시지가있을 때만 서버가 클라이언트에 메시지를 보내는 방법을 궁금합니다. 이 내 확장 처리 기능입니다 :PHP, 웹 소켓 및 MySQL을 사용하여 채팅

function refreshchat() { 

try { 
    socket.send('{"token":"' + token + '","userid":'+ userid +'"chatid":' + chatid + ',"limit":' + limit + '}'); 

} catch (ex) { 
    console.log(ex); 
} 
setTimeout(refreshchat, 3000); 

}

내가 통관 PHP에서 인증 물건을 생략 :

protected function process($user, $message) { 
    $databaseHandler = mysqli_connect('blahblah'); 
    $decoded = json_decode($message, true); 
    $chat_id = $decoded['chatid']; 
    $limit = $decoded['limit']; 
    $user_id = filterString($decoded['userid'], $databaseHandler); 
    $SQLQuery = "SELECT chat_messages.message, users.name FROM chat_messages JOIN users ON chat_messages.user_id=users.user_id WHERE chat_messages.chat_id = '$chat_id' ORDER BY chat_messages.message_id DESC LIMIT $limit,5;"; 
    $SQLResult = mysqli_query($databaseHandler, $SQLQuery); 
    $i = 0; 
    $arr = array(); 
    while ($row = mysqli_fetch_assoc($SQLResult)) { 
     $i++; 
     $arr[$i] = $row['name'] . ': ' . $row['message']; 
    } 


    $this->send($user, json_encode($arr)); 

} 

은 JS 함수이다.

미리 감사드립니다.

답변

0

글쎄 setTimeout JavaScript 함수를 사용하고 있습니다. 그것은 한 번만 실행됩니다. setInterval 함수를 사용할 수 있습니다. 반복적으로 실행됩니다. (http://www.w3schools.com/jsref/met_win_setinterval.asp)

서버가 클라이언트에게 새로운 채팅 메시지가 있음을 알리는 기능이 필요합니다. 나는 자바 스크립트에서 타이머를 사용하는 것이 좋은 선택이라고 생각한다. 푸시 알림 api : https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web을 확인할 수도 있습니다.