Skip to content

Commit f51b471

Browse files
author
ithewei
committed
Test EventSource
1 parent a69cd46 commit f51b471

File tree

4 files changed

+58
-4
lines changed

4 files changed

+58
-4
lines changed

examples/httpd/handler.cpp

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -287,13 +287,17 @@ int Handler::upload(const HttpContextPtr& ctx) {
287287

288288
int Handler::sse(const HttpContextPtr& ctx) {
289289
ctx->writer->EndHeaders("Content-Type", "text/event-stream");
290-
// send(time) every 1s
290+
// send(message) every 1s
291291
hv::setInterval(1000, [ctx](hv::TimerID timerID) {
292292
char szTime[DATETIME_FMT_BUFLEN] = {0};
293293
datetime_t now = datetime_now();
294294
datetime_fmt(&now, szTime);
295-
ctx->writer->write("event: timeout\n");
296-
ctx->writer->write(hv::asprintf("data: %s\n\n", szTime));
295+
// @test html/EventSource.html EventSource.onmessage
296+
std::string msg("event: message\n");
297+
msg += "data: ";
298+
msg += szTime;
299+
msg += "\n\n";
300+
ctx->writer->write(msg);
297301
});
298302
return HTTP_STATUS_UNFINISHED;
299303
}

examples/httpd/router.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,5 +135,5 @@ void Router::Register(hv::HttpService& router) {
135135
router.POST("/upload", Handler::upload);
136136

137137
// SSE: Server Send Events
138-
router.GET("/SSE", Handler::sse);
138+
router.GET("/sse", Handler::sse);
139139
}

html/EventSource.html

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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>
File renamed without changes.

0 commit comments

Comments
 (0)