I am trying to implement a server client project which needs the server to send data to the client every 5 minutes with the client only asking in the beginning of connection. Server-sent events seem to be the go-to solution.
I have tried to use the functions given in the Javalin Documents. I am able to receive a response with a simple get from the server. But I couldn't establish a sse connection. The code enters the lambda function in the server but the client does not receive anything. I am not sure if the client or the server, or even both have a problem. The only output we get from the codes below is "connected" on the server side. Thank you in advance.
Code for the server
import io.javalin.Javalin;
public class SimpleTwitter {
public static void main(String[] args) {
Javalin app = Javalin.create().start(7000);
app.sse("/sse", client ->{
System.out.println("connected");
client.sendEvent("message","Hello, SSE");
client.onClose(() -> System.out.println("Client disconnected"));
});
app.get("/", ctx -> ctx.result("Hello World"));
}
}
Code for the client
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("http://localhost:7000/sse");
source.onmessage = function(event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
Turns out the problem was not the code. By looking at the developer tools on chrome, we saw the following:
"Access to resource at 'http://localhost:7000/sse' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
When we installed a chrome extention called "Allow-Control-Allow-Origin: *", we were able to see the output.
Also, here are the updated better working codes:
> <<!DOCTYPE html> <html> <body>
>
> <h1>Tweets</h1>
>
> <script> new
> EventSource('http://localhost:7000/sse').addEventListener( "hi", msg
> =>{ document.write(msg.data); }); </script>
>
> </body> </html>
...
public static void main(String[] args) throws InterruptedException {
Queue<SseClient> clients = new ConcurrentLinkedQueue<>();
Javalin app = Javalin.create().start(7000);
app.sse("/sse", client -> {
clients.add(client);
client.onClose(() -> clients.remove(client));
});
while (true) {
for (SseClient client : clients) {
client.sendEvent("hi", "hello world");
}
TimeUnit.SECONDS.sleep(1);
}
}