Created
December 5, 2015 06:55
-
-
Save tomoTaka01/976284c455ae7f0afd6b to your computer and use it in GitHub Desktop.
HTML file for Server Sent Event JavaScript Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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