File tree Expand file tree Collapse file tree 2 files changed +69
-0
lines changed
java/com/packtpub/javaee8 Expand file tree Collapse file tree 2 files changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .packtpub .javaee8 ;
2
+
3
+ import javax .annotation .PostConstruct ;
4
+ import javax .enterprise .context .ApplicationScoped ;
5
+ import javax .ws .rs .*;
6
+ import javax .ws .rs .core .Context ;
7
+ import javax .ws .rs .core .MediaType ;
8
+ import javax .ws .rs .core .Response ;
9
+ import javax .ws .rs .sse .OutboundSseEvent ;
10
+ import javax .ws .rs .sse .Sse ;
11
+ import javax .ws .rs .sse .SseBroadcaster ;
12
+ import javax .ws .rs .sse .SseEventSink ;
13
+
14
+ @ ApplicationScoped
15
+ @ Path ("broadcast" )
16
+ public class BroadcastResource {
17
+
18
+ @ Context
19
+ private Sse sse ;
20
+ private SseBroadcaster sseBroadcaster ;
21
+
22
+ @ PostConstruct
23
+ public void initialize () {
24
+ sseBroadcaster = sse .newBroadcaster ();
25
+ }
26
+
27
+ @ GET
28
+ @ Produces (MediaType .SERVER_SENT_EVENTS )
29
+ public void fetch (@ Context SseEventSink sseEventSink ) {
30
+ sseBroadcaster .register (sseEventSink );
31
+ }
32
+
33
+ @ POST
34
+ @ Consumes (MediaType .APPLICATION_FORM_URLENCODED )
35
+ public Response broadcast (@ FormParam ("message" ) String message ) {
36
+ OutboundSseEvent broadcastEvent = sse .newEvent ("message" , message );
37
+ sseBroadcaster .broadcast (broadcastEvent );
38
+ return Response .noContent ().build ();
39
+ }
40
+ }
Original file line number Diff line number Diff line change
1
+ <%@ page contentType =" text/html;charset=UTF-8" language =" java" %>
2
+ <!DOCTYPE html>
3
+ <html >
4
+ <head >
5
+ <title >Simple SSE broadcast</title >
6
+ </head >
7
+ <body >
8
+
9
+ <form action =" /sse-service/api/broadcast" method =" post" >
10
+ Message <input type =" text" name =" message" />
11
+ <input type =" submit" value =" Submit" />
12
+ </form >
13
+
14
+ <h2 >Chat messages</h2 >
15
+ <div id =" messages" ></div >
16
+
17
+ <script >
18
+ if (typeof (EventSource ) !== " undefined" ) {
19
+ var source = new EventSource (" http://localhost:8080/sse-service/api/broadcast" );
20
+
21
+ source .addEventListener (" message" , function (e ) {
22
+ document .getElementById (" messages" ).innerHTML += e .data + " <br>" ;
23
+ }, false );
24
+ } else {
25
+ document .getElementById (" messages" ).innerHTML = " Sorry, your browser does not support server-sent events..." ;
26
+ }
27
+ </script >
28
+ </body >
29
+ </html >
You can’t perform that action at this time.
0 commit comments