44// port from https://github.com/seanmonstar/warp/blob/master/examples/sse_chat.rs 
55
66use  std:: collections:: HashMap ; 
7- use  std:: result:: Result  as  IoResult ; 
87use  std:: sync:: atomic:: { AtomicUsize ,  Ordering } ; 
98
10- use  futures_util:: { future ,   FutureExt ,   Stream ,  StreamExt ,  TryFutureExt ,  TryStreamExt } ; 
9+ use  futures_util:: { Stream ,  StreamExt ,  TryFutureExt ,  TryStreamExt } ; 
1110use  once_cell:: sync:: Lazy ; 
1211use  parking_lot:: Mutex ; 
1312use  tokio:: sync:: mpsc; 
1413use  tokio_stream:: wrappers:: UnboundedReceiverStream ; 
1514
1615use  silent:: prelude:: * ; 
17- use  silent:: sse:: { self ,  keep_alive} ; 
1816
1917type  Users  = Mutex < HashMap < usize ,  mpsc:: UnboundedSender < Message > > > ; 
2018
@@ -55,7 +53,7 @@ async fn chat_send(req: Request) -> Result<Response> {
5553    Ok ( Response :: empty ( ) ) 
5654} 
5755
58- fn  get_connected ( _req :  Request )  -> impl   Stream < Item  =  Result < sse :: Event > >  +  Send  +  ' static  { 
56+ async   fn  user_connected ( _req :  Request )  -> Result < Response >  { 
5957    // Use a counter to assign a new unique ID for this user. 
6058    let  my_id = NEXT_USER_ID . fetch_add ( 1 ,  Ordering :: Relaxed ) ; 
6159
@@ -75,47 +73,16 @@ fn get_connected(_req: Request) -> impl Stream<Item = Result<sse::Event>> + Send
7573
7674    // Convert messages into Server-Sent Events and returns resulting stream. 
7775    let  stream = rx. map ( |msg| match  msg { 
78-         Message :: UserId ( my_id)  => Ok ( sse:: Event :: default ( ) . event ( "user" ) . data ( my_id. to_string ( ) ) ) , 
79-         Message :: Reply ( reply)  => Ok ( sse:: Event :: default ( ) . data ( reply) ) , 
76+         Message :: UserId ( my_id)  => { 
77+             warn ! ( "user {} disconnected" ,  my_id) ; 
78+             Ok ( SSEEvent :: default ( ) . event ( "user" ) . data ( my_id. to_string ( ) ) ) 
79+         } 
80+         Message :: Reply ( reply)  => { 
81+             warn ! ( "sse_reply: {}" ,  reply) ; 
82+             Ok ( SSEEvent :: default ( ) . data ( reply) ) 
83+         } 
8084    } ) ; 
81-     stream
82- } 
83- 
84- async  fn  user_connected ( _req :  Request )  -> Result < Response >  { 
85-     let  stream = get_connected ( _req) ; 
86-     // SseKeepAlive::new(stream).streaming(res).ok(); 
87-     let  mut  res = Response :: empty ( ) 
88-         . set_header ( 
89-             HeaderName :: from_static ( "Content-Type" ) , 
90-             HeaderValue :: from_static ( "text/event-stream" ) , 
91-         ) 
92-         . set_header ( 
93-             HeaderName :: from_static ( "Cache-Control" ) , 
94-             HeaderValue :: from_static ( "no-cache" ) , 
95-         ) 
96-         . set_header ( 
97-             HeaderName :: from_static ( "Connection" ) , 
98-             HeaderValue :: from_static ( "keep-alive" ) , 
99-         ) 
100-         . set_header ( 
101-             HeaderName :: from_static ( "Access-Control-Allow-Origin" ) , 
102-             HeaderValue :: from_static ( "*" ) , 
103-         ) ; 
104-     res. set_status ( StatusCode :: PARTIAL_CONTENT ) ; 
105-     // res.set_body(stream_body(stream)); 
106-     let  event_stream = sse:: keep_alive ( ) . stream ( stream) ; 
107-     let  body_stream = event_stream
108-         . map_err ( |error| { 
109-             // FIXME: error logging 
110-             error ! ( "sse stream error: {}" ,  error) ; 
111-             SilentError :: BusinessError  { 
112-                 code :  StatusCode :: INTERNAL_SERVER_ERROR , 
113-                 msg :  "sse::keep error" . to_string ( ) , 
114-             } 
115-         } ) 
116-         . into_stream ( ) 
117-         . and_then ( |event| future:: ready ( Ok ( event. to_string ( ) ) ) ) ; 
118-     res. set_body ( stream_body ( body_stream) ) ; 
85+     let  res = sse_reply ( stream) ; 
11986    Ok ( res) 
12087} 
12188
@@ -148,40 +115,38 @@ static INDEX_HTML: &str = r#"
148115        <title>SSE Chat</title> 
149116    </head> 
150117    <body> 
151-         <h1>SSE Chat </h1> 
118+         <h1>SSE chat </h1> 
152119        <div id="chat"> 
153120            <p><em>Connecting...</em></p> 
154121        </div> 
155-         <input type="text" id="msg" /> 
156-         <button type="button" id="submit">Send</button> 
157-         <script> 
158-         const chat = document.getElementById('chat'); 
159-         const msg = document.getElementById('msg'); 
160-         const submit = document.getElementById('submit'); 
161-         let sse = new EventSource(`http://${location.host}/chat`); 
122+         <input type="text" id="text" /> 
123+         <button type="button" id="send">Send</button> 
124+         <script type="text/javascript"> 
125+         var uri = 'http://' + location.host + '/chat'; 
126+         var sse = new EventSource(uri); 
127+         function message(data) { 
128+             var line = document.createElement('p'); 
129+             line.innerText = data; 
130+             chat.appendChild(line); 
131+         } 
162132        sse.onopen = function() { 
163133            chat.innerHTML = "<p><em>Connected!</em></p>"; 
164134        } 
165-         var userId ; 
135+         var user_id ; 
166136        sse.addEventListener("user", function(msg) { 
167-             userId  = msg.data; 
137+             user_id  = msg.data; 
168138        }); 
169139        sse.onmessage = function(msg) { 
170-             showMessage (msg.data); 
140+             message (msg.data); 
171141        }; 
172-         document.getElementById('submit') .onclick = function() { 
142+         send .onclick = function() { 
173143            var msg = text.value; 
174144            var xhr = new XMLHttpRequest(); 
175-             xhr.open("POST", `${ uri}/${ user_id}` , true); 
145+             xhr.open("POST", uri + '/' +  user_id, true); 
176146            xhr.send(msg); 
177147            text.value = ''; 
178-             showMessage ('<You>: ' + msg); 
148+             message ('<You>: ' + msg); 
179149        }; 
180-         function showMessage(data) { 
181-             const line = document.createElement('p'); 
182-             line.innerText = data; 
183-             chat.appendChild(line); 
184-         } 
185150        </script> 
186151    </body> 
187152</html> 
0 commit comments