2012-10-18 2 views
0

이 투표 결과는 절대적으로 가치가없는 실제 질문이 아닙니다.jquery/ajax long-polling php mysql codeigniter

Google에서 한 달 넘게 검색하고 검색 한 결과 실제로이라는 php 및 mysql을 사용하여 긴 폴링을 수행하는 정확한 예제를 찾을 수 없습니다. 가급적이면 mysql 및 codeigniter를 사용하여 ajax long polling 예제를 찾고 싶습니다.

누구나이 질문을 제기하며 좋은 예를 들어 알려주세요.

내가 읽고있는 아약스를 알고 있다고 생각하는 사람은 나를 이메일로 보내거나 여기에서 알려주세요. Codeigniter를 거의 사용하여 채팅 앱을 사용하고 있지만 클라이언트 쪽에서 jquery/ajax long polling 부분에 문제가 있습니다. 마지막으로 다른 채팅 앱을 게시했기 때문에이 채팅 앱을 게시하지 않았습니다. 여기에 다른 개발자가 게시 한 코드가 너무 많아서 불만이 있습니다. 실제로 작동하는 Ajax 긴 폴링 코드를 실제로 제공 할 수있는 모든 사람에게이 코드를 보낼 준비가되었습니다.

고마워요.

+0

아약스가 좋지 않은 선택인데 웹 소켓을 사용합니다. 이것은 보시다시피 질문에 대답 한 것 같습니다 - http://stackoverflow.com/questions/333664/simple-long-polling-example-code – daxroc

+1

안녕하세요 daxroc. 예는 웹 소켓 예를 통해 왔지만 아무도 작동하지 않았습니다. 플러스 웹 소켓은 모든 브라우저와 호환되지 않습니다. 왜냐하면이 유형의 밀교 프로그래밍은 아약스의 긴 폴링에 비해 상당히 새롭기 때문에 내가 가장 강력하게 말하는 방법은 아닙니다. 또한 다른 해결책으로 혜성을보고 있습니다. 당신이 생각하는 것을 말해 줄 수 있습니다. 도움을 주셔서 감사드립니다. 지금은 작동하지만 작업을 완료하지만 코드가 필요합니다. 당신이 훌륭한 예제를 알고 있다면 효과가있을 것입니다. 저에게 알려주세요. 내 질문에 투표하지 않거나 진짜 질문이 아니기 때문에 폐회 해 주셔서 감사합니다. – eNigma

답변

5

채팅 메시지를 db에 저장한다고 가정합니다. 그래서 하나의 접근 방식은 다음과 같이 보일 것입니다 :

가장 중요한 것은 처음 사용자가 서버 시간에 전달해야 할 필요가 있다는 것입니다. 이것은 새로운 채팅 메시지를 얻기위한 열쇠이므로 먼저

URL을 "http://yoursite.com/chat/get_time"에 따라
var time; 
$.ajax({ 
    url: 'http://yoursite.com/chat/get_time', 
    success: function(dataReponse) { 
     time = dataResponse; 
    }, 
    type: 'GET' 
}); 

, 당신은 "get_time"의 이름, 응답이 기능이 필요 밀리 초 단위로 서버 시간과 기능을 "chat"라는 이름의 컨트롤러가 필요합니다, 그래서 우리는이 작업을 수행 :

, 우리는 할
function get_time() { 
    echo time(); 
} 
function getNewMsgs() { 
    $.ajax({ 
     url: 'http://yoursite.com/chat/get_new_msgs', 
     type: 'POST', 
     // send the time 
     data: { time: time }, 
     success: function(dataResponse) { 
      try { 
       dataResponse = JSON.parse(dataResponse); 
       // update the time 
       time = dataResponse.time; 
       // show the new messages 
       dataResponse.msgs.forEach(function(msg) { 
        console.log(msg); 
       }); 
         // repeat 
         setTimeout(function() { 
          getNewMsgs(); 
         }, 1000); 
      } catch(e) { 
       // may fail is the connection is lost/timeout for example, so dataResponse 
       // is not a valid json string, in this situation you can start this process again 
      } 
     } 
    }); 
} 

comebacj 컨트롤러 "chat"에, 우리는 "get_new_msgs" 기능을 코딩해야합니다 : 414,지금 우리가 이렇게 서버 새 채팅 메시지에 폴링 시작 "chat_msg" 모델

function get_new_msgs() { 

    $this->load->model('chat_msg'); 
    echo json_encode(array(
     'msgs' => $this->chat_msg->start_polling(), 
     // response again the server time to update the "js time variable" 
     'time' => time() 
    )); 
} 

을, 우리 코드 "start_polling" 함수 :

function start_polling() { 
    // get the time 
    $time = $this->input->post('time'); 
    // some crappy validation 
    if(!is_numeric($time)) { 
     return array(); 
    } 

    $time = getdate($time); 
    // -> 2010-10-01 
    $time = $time['year'] '-' + $time['mon'] + '-' + $time['mday']; 

    while(true) { 

     $this->db->select('msg'); 
     $this->db->from('chat_msg'); 
     $this->db->where('time >=', $time); 
     $this->db->order_by('posted_time', 'desc'); 
     $query = $this->db->get(); 

     if($query->num_rows() > 0) { 
      $msgs = array(); 
      foreach($query->result() as $row) { 
       $msgs[] = $row['msg']; 
      } 
      return $msgs; 
     } 

     sleep(1); 
    } 
} 

경고를 받겠습니다.이 코드를 내 마음에 썼습니다. 웹이 없습니다. 이 코드를 테스트하기 위해이 순간 나의 처분에 맞춰라.

+0

이것은 어떻게 CodeIgniter와 관련이 있습니까? –

+0

??? PHP 코드는 CI 기반 – nobody

+0

Fine입니다. 괜찮아. 나는 단지 확인하고 싶었다! –