| 1 |
<!DOCTYPE HTML> |
| 2 |
<html> |
| 3 |
|
| 4 |
<head> |
| 5 |
<meta charset="utf-8"> |
| 6 |
<title>EventSource客户端</title> |
| 7 |
|
| 8 |
<script type="text/javascript"> |
| 9 |
function EventSourceTest(url) |
| 10 |
{ |
| 11 |
if (typeof(EventSource) !== "undefined") |
| 12 |
{ |
| 13 |
var es = new EventSource(url); |
| 14 |
|
| 15 |
es.onopen = function() |
| 16 |
{ |
| 17 |
alert("连接已建立"); |
| 18 |
}; |
| 19 |
|
| 20 |
es.onmessage = function(ev) |
| 21 |
{ |
| 22 |
console.log("received event: " + ev.data); |
| 23 |
var li=document.createElement("li"); |
| 24 |
li.innerHTML=ev.data; |
| 25 |
document.getElementById("msg_list").appendChild(li); |
| 26 |
}; |
| 27 |
|
| 28 |
es.onerror = function(e) |
| 29 |
{ |
| 30 |
alert("连接断开"); |
| 31 |
}; |
| 32 |
} |
| 33 |
else |
| 34 |
{ |
| 35 |
alert("您的浏览器不支持 EventSource!"); |
| 36 |
} |
| 37 |
} |
| 38 |
</script> |
| 39 |
</head> |
| 40 |
|
| 41 |
<body> |
| 42 |
URL: <input type="text" id="url" value="http://127.0.0.1:8080/sse" style="width:300px;"> |
| 43 |
<button onclick="EventSourceTest(document.getElementById('url').value)">运行 EventSource</button> |
| 44 |
<div> |
| 45 |
<ul id="msg_list" style="height:500px;overflow-y:scroll;"> |
| 46 |
</ul> |
| 47 |
<div> |
| 48 |
</body> |
| 49 |
|
| 50 |
</html> |