-
-
Save eduard-vasinskyi/65287c900a70288a1b298a9027b26ca5 to your computer and use it in GitHub Desktop.
A demo of using DataKernel for Server Sent Events
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
import io.datakernel.bytebuf.ByteBufStrings; | |
import io.datakernel.csp.ChannelSupplier; | |
import io.datakernel.di.annotation.Provides; | |
import io.datakernel.http.AsyncServlet; | |
import io.datakernel.http.HttpHeaders; | |
import io.datakernel.http.HttpResponse; | |
import io.datakernel.http.RoutingServlet; | |
import io.datakernel.launchers.http.HttpServerLauncher; | |
import io.datakernel.promise.Promises; | |
import java.text.DateFormat; | |
import java.text.SimpleDateFormat; | |
import java.time.Duration; | |
import java.util.Date; | |
public final class ServerSentEventsDemo extends HttpServerLauncher { | |
private static final DateFormat DATE_FORMATTER = new SimpleDateFormat("HH:mm:ss"); | |
private static final String HTML = "<h1>Open developer console to see server-sent messages</h1>" + | |
"<script>new EventSource(\"/sse\").onmessage = event => console.log(\"message: \" + event.data)</script>\n"; | |
@Provides | |
public AsyncServlet mainServlet() { | |
return RoutingServlet.create() | |
.map("/", request -> HttpResponse.ok200().withHtml(HTML)) | |
.map("/sse", request -> HttpResponse.ok200() | |
.withHeader(HttpHeaders.CONTENT_TYPE, "text/event-stream") | |
.withBodyStream(ChannelSupplier.of(() -> Promises.delay(Duration.ofSeconds(1), new Date()) | |
.map(ServerSentEventsDemo::encodeDateAsEvent) | |
.map(ByteBufStrings::wrapUtf8)))); | |
} | |
private static String encodeDateAsEvent(Date date) { | |
String formattedDate = DATE_FORMATTER.format(date); | |
return "data: {time: " + formattedDate + "}\n\n"; | |
} | |
public static void main(String[] args) throws Exception { | |
new ServerSentEventsDemo().launch(args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Many thanks for this example!