comparison src/goodjava/webserver/ServerSentEvents.java @ 1740:c9c974817d0c

add ServerSentEvents.sweep
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 03 Nov 2022 22:05:11 -0600
parents 9713f7fd50b3
children 623d9f62ab92
comparison
equal deleted inserted replaced
1739:3e9f26404433 1740:c9c974817d0c
9 import java.util.ArrayList; 9 import java.util.ArrayList;
10 import java.util.Map; 10 import java.util.Map;
11 import java.util.HashMap; 11 import java.util.HashMap;
12 import java.util.Collections; 12 import java.util.Collections;
13 import java.util.Iterator; 13 import java.util.Iterator;
14 import java.util.Timer;
15 import java.util.TimerTask;
16 import goodjava.logging.Logger;
17 import goodjava.logging.LoggerFactory;
14 18
15 19
16 public class ServerSentEvents { 20 public class ServerSentEvents {
21 private static final Logger logger = LoggerFactory.getLogger(ServerSentEvents.class);
17 22
18 private static class Con { 23 private static class Con {
19 final Socket socket; 24 final Socket socket;
20 final Writer writer; 25 final Writer writer;
21 26
43 writer.flush(); 48 writer.flush();
44 } catch(IOException e) { 49 } catch(IOException e) {
45 iter.remove(); 50 iter.remove();
46 } 51 }
47 } 52 }
48 if( cons.isEmpty() ) 53 if( cons.isEmpty() ) {
49 map.remove(url); 54 map.remove(url);
55 //logger.info("removed "+url);
56 }
50 } 57 }
51 } 58 }
52 59
53 private static final Map<String,EventHandler> map 60 private static final Map<String,EventHandler> map
54 = Collections.synchronizedMap(new HashMap<String,EventHandler>()); 61 = Collections.synchronizedMap(new HashMap<String,EventHandler>());
90 97
91 public static void writeMessage( String url, String message ) { 98 public static void writeMessage( String url, String message ) {
92 write( url, toData(message) ); 99 write( url, toData(message) );
93 } 100 }
94 101
102 private static void sweep() {
103 List<String> urls;
104 synchronized(map) {
105 urls = new ArrayList<String>(map.keySet());
106 }
107 for( String url : urls ) {
108 write( url, "event: ping\n" );
109 }
110 }
111
112 private static final Timer sweeper = new Timer("ServerSentEvents",true);
113 static {
114 long period = 1000L*60*60; // hour
115 TimerTask task = new TimerTask() {
116 public void run() {
117 sweep();
118 }
119 };
120 sweeper.schedule(task,period,period);
121 }
122
95 private ServerSentEvents() {} // never 123 private ServerSentEvents() {} // never
96 } 124 }