HTML, CSS, jQuery를 사용하는 대화 패널이 있습니다. 아무 문제없이 이벤트 리스너를 설정하십시오. 아무 문제없이 클라이언트에게 메시지를 보낼 수있는 텍스트/이벤트 스트림 PHP 파일을 설정하십시오. 클라이언트에서 새 메시지를 받으면 이벤트 스트림이 열려있는 모든 사용자에게 메시지를 브로드 캐스트하도록 클라이언트에서이 서버 스크립트로 어떻게 통신합니까? 서버는 새 메시지를 받으면 이벤트를 보내야합니다.서버 보낸 이벤트 - 이벤트 스트림 - PHP 서버 사이드 이벤트 트리거?
다음header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
while (1) {
if ($newMessage){ //How does $newMessage get filled in an already running script?
echo "id: 1234\n";
echo "event: ping\n";
echo 'data: {"newMessage": "' . $newMessage . '"}';
echo "\n\n";
}
ob_flush();
flush();
sleep(1);
}
은 JS입니다 : 여기
는 message_sender.php입니다
var evtSource = new EventSource("message_sender.php");
evtSource.onmessage = function(e) {
}
evtSource.addEventListener("ping", function(e) {
var newElement = document.createElement("li");
var obj = JSON.parse(e.data);
newElement.innerHTML = "ping " + obj.newMessage;
$('#chat_panel').append(newElement);
}, false);
evtSource.onerror = function(e) {
alert("EventSource failed.");
};
$('#message_form').submit(function(e){
e.preventDefault();
var message = $('#txtb_chat').val();
$.ajax({
type: 'POST',
dataType: 'json',
data: message,
url: 'message_processor.php',
beforeSend: function(){
},
success: function(){
$('#txtb_chat').val("");
}
});
return false;
});
응답 해 주셔서 감사합니다. mysql db를 사용하는 대신에 이것을 메모리에서 처리하는 방법이 있었으면합니다. db보다 나은 방법이 없을 수도 있습니다. – carter
@carter Redis와 같은 메모리 내장 데이터베이스를 사용할 수 있습니다. – Kornel