Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTML file for Server Sent Event JavaScript Sample
<!DOCTYPE html>
<html>
<head>
<title>Server Sent Event Sample</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Server Sent Event Sample</h2>
<div>
<label>Task count:</label>
<input type="number" id="task_count" />
<label>Task interval:</label>
<input type="number" id="task_interval" />
</div>
<div>
<button id="sendBtn">Server Send Event Start</button>
<button id="closeBtn">Server Send Event Close</button>
</div>
<div>
<h3>Received Messages</h3>
<output id="result"></output>
</div>
<script>
'usestrict';
(function(){
var sendBtn = document.getElementById('sendBtn');
var closeBtn = document.getElementById('closeBtn');
var result = document.getElementById('result');
var eventSource = null;
// close button click event
closeBtn.addEventListener('click', function(){
if (eventSource){
eventSource.close();
}
});
// start button click event
sendBtn.addEventListener('click', function(){
if (typeof (EventSource) !== void 0){
//EventSource がサポートされている場合
result.insertAdjacentHTML('beforeend',
'<li>EventSource supported!</li>');
var taskCnt = document.getElementById('task_count').value;
var taskInterval = document.getElementById('task_interval').value;
var url = 'http://localhost:8080/event/'
+ taskCnt + '/' + taskInterval + '/';
eventSource = new EventSource(url);
eventSource.addEventListener('message-client', function(event){
result.insertAdjacentHTML('beforeend',
'<li>' + event.data + '</li>');
});
eventSource.onerror = function(){
result.insertAdjacentHTML('beforeend',
'<li>EventSource Error!</li>');
eventSource.close();
};
} else {
//EventSource がサポートされていない場合
result.insertAdjacentHTML('beforeend',
'<li>not support EventSource</li>');
}
});
}());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.