text/event-stream协议

客户端接收 text/event-stream

html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Event Stream Demo</title>
		<style type="text/css">
			body {
				font-family: Arial, sans-serif;
				text-align: center;
			}
			#event-stream-data {
				margin: 50px auto;
				max-width: 600px;
				border: 1px solid #ccc;
				padding: 10px;
			}
		</style>
	</head>
	<body>
		<div id="event-stream-data"></div>

		<script>
			const eventStreamDataElement = document.getElementById('event-stream-data');
			function handleEventStreamMessage(event) {
				console.log(event)
				const eventText = event.data;
				displayEvent(eventText);
			}

			function displayEvent(eventText) {
				const eventElement = document.createElement('p');
				eventElement.textContent = eventText;
				eventStreamDataElement.appendChild(eventElement);
			}

			function connectToEventStream() {
				fetch('http://localhost:8004/website/events', {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json'
						},
						body: JSON.stringify({
							data: 'example'
						}) // Replace with your POST data
					})
					.then(response => {
						const reader = response.body.getReader();
						const decoder = new TextDecoder();

						return reader.read().then(function processResult(result) {
							console.log(result)
							if (result.done) {
								return;
							}

							const chunk = decoder.decode(result.value, {
								stream: true
							});
							handleEventStreamMessage({
								data: chunk
							});

							return reader.read().then(processResult);
						});
					})
					.catch(error => {
						console.error('Error occurred while fetching event stream:', error);
					});
			}
			connectToEventStream();
		</script>
	</body>
</html>

服务端发送(springboot)

    @PostMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter eventStream(@RequestBody Object obj) {
        SseEmitter emitter = new SseEmitter();
        System.out.println(obj.toString());
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(() -> {
            try {
                // 模拟产生一条事件数据
                String eventData = "Event data: " + System.currentTimeMillis();
                emitter.send(SseEmitter.event().data(eventData));
            } catch (IOException e) {
                emitter.complete();
            }
        }, 0, 1, TimeUnit.SECONDS);
        return emitter;
    }

posted @ 2023-07-27 17:28  天葬  阅读(2642)  评论(0编辑  收藏  举报