채팅 메시지를 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);
}
}
경고를 받겠습니다.이 코드를 내 마음에 썼습니다. 웹이 없습니다. 이 코드를 테스트하기 위해이 순간 나의 처분에 맞춰라.
아약스가 좋지 않은 선택인데 웹 소켓을 사용합니다. 이것은 보시다시피 질문에 대답 한 것 같습니다 - http://stackoverflow.com/questions/333664/simple-long-polling-example-code – daxroc
안녕하세요 daxroc. 예는 웹 소켓 예를 통해 왔지만 아무도 작동하지 않았습니다. 플러스 웹 소켓은 모든 브라우저와 호환되지 않습니다. 왜냐하면이 유형의 밀교 프로그래밍은 아약스의 긴 폴링에 비해 상당히 새롭기 때문에 내가 가장 강력하게 말하는 방법은 아닙니다. 또한 다른 해결책으로 혜성을보고 있습니다. 당신이 생각하는 것을 말해 줄 수 있습니다. 도움을 주셔서 감사드립니다. 지금은 작동하지만 작업을 완료하지만 코드가 필요합니다. 당신이 훌륭한 예제를 알고 있다면 효과가있을 것입니다. 저에게 알려주세요. 내 질문에 투표하지 않거나 진짜 질문이 아니기 때문에 폐회 해 주셔서 감사합니다. – eNigma