官术网_书友最值得收藏!

Building a UI with SSE support

The last thing that we need in order to complete our use case is an HTML page with some JavaScript code to communicate with the server. For the sake of conciseness, we will strip all HTML tags and leave only the minimum that is required to achieve a result, as follows:

<body>
<ul id="events"></ul>
<script type="application/javascript">
function add(message) {
const el = document.createElement("li");
el.innerHTML = message;
document.getElementById("events").appendChild(el);
}

var eventSource = new EventSource("/temperature-stream"); // (1)
eventSource.onmessage = e => { // (2)
const t = JSON.parse(e.data);
const fixed = Number(t.value).toFixed(2);
add('Temperature: ' + fixed + ' C');
}
eventSource.onopen = e => add('Connection opened'); // (3)
eventSource.onerror = e => add('Connection closed'); //
</script>
</body>

Here, we are using the EventSource object pointed at /temperature-stream (1). This handles incoming messages by invoking the onmessage() function (2), error handling, and reaction to the stream opening, which are done in the same fashion (3). We should save this page as index.html and put it in the src/main/resources/static/ folder of our project. By default, Spring Web MVC serves the content of the folder through HTTP. Such behavior could be changed by providing a configuration that extends the WebMvcConfigurerAdapter class. 

主站蜘蛛池模板: 安溪县| 蒙阴县| 玛沁县| 蒙阴县| 太康县| 克山县| 泰州市| 游戏| 射阳县| 鄂托克旗| 福贡县| 子洲县| 宣恩县| 阿城市| 玛多县| 灵石县| 泰州市| 荥阳市| 哈尔滨市| 共和县| 曲沃县| 江山市| 莱西市| 都匀市| 泽普县| 平顶山市| 施甸县| 永春县| 普安县| 阿鲁科尔沁旗| 噶尔县| 兰州市| 通江县| 库车县| 江口县| 泰来县| 津南区| 临西县| 玛纳斯县| 昆山市| 绵阳市|