lundi 4 novembre 2019

Server Sent Events

I have an issue with server-sent events. Message pushed by the server doesn't receive at the client End. I changed the message format a lot of time still it doesn't work. am using plain strut 2. Are there any changes that need to do in struts?

Here is my java code

    public final class ClientEventEmitter extends HttpServlet{

    private static ConcurrentHashMap<String,ClientEvent> store = new ConcurrentHashMap<String,ClientEvent>();   
    private static final Logger LOGGER  = Logger.getLogger(ClientEventEmitter.class.getName());

    private static final int CASE1 = 1;
    private static final int CASE2 = 2;

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        handler(request,response);
    }   

    public void doPost(HttpServletRequest request ,HttpServletResponse response) {
        handler(request,response);
    }   

    private void handler(HttpServletRequest request ,HttpServletResponse response) {

        response.setContentType("text/event-stream");
        request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);                  
        response.setHeader("Connection", "Keep-Alive");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("X-Accel-Buffering", "no");
        response.setCharacterEncoding("UTF-8");

        String key = request.getParameter("key");
        int type =  Integer.parseInt(request.getParameter("connection-type"));              

        ClientEvent event = null;       
        switch(type) {
            case ClientEventEmitter.CASE1:                  
                    event  = SampleEvent.getEventInstance(key, request, response);
                break;
            case ClientEventEmitter.CASE2:
                break;          
            default:
                LOGGER.log(Level.SEVERE,"Invalid Connection-type received connection-type={0}",type);
        }

        if(event!=null) {
            LOGGER.log(Level.INFO,"Async Context key={0} event={1}",new Object[] {type,event});
            store.put(key, event);
            event.sendNotification(key,"test");         
        }
        else {
            try {
                response.getWriter().write("Exception while creating Connection");
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE,"Exception while creating async connection ");
            }
        }
    }

}

SampleEvent.Java

 public class SampleEvent implements ClientEvent{

    private AsyncContext context = null;
    private String key = null;

    public static final long ASYNC_THREAD_TIMEOUT = 3600000;
    public static final String MESSAGE_SEPARATOR = "\n";
    private static final long RETRY_TIMEOUT = 3600000;

    private static final Logger LOGGER = Logger.getLogger(SampleEvent.class.getName());

    private SampleEvent(String key,AsyncContext context) {
        this.context = context;
        this.key = key;
        this.context.setTimeout(SampleEvent.ASYNC_THREAD_TIMEOUT);
        this.context.addListener(this.getAsyncListener(this));
        this.writeMessage(this.getRetryString(RETRY_TIMEOUT));          
    }


    public void closeClient() {
        this.writeMessage(this.getEvent("closed"));
        this.context.complete();
        ClientEventEmitter.removeEvent(this.key);
    }


    private void writeMessage(String message) {
        PrintWriter out =null;
        LOGGER.log(Level.INFO,"Writing Message to Server Send Event Stream {0}",message);
        try {
            out = this.context.getResponse().getWriter();
            out.write(message);     
            out.write(MESSAGE_SEPARATOR);
            out.flush();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE,"Exception while writing message in Event Streams ",e);
        }       
    }


      public void sendNotification(String message) {          
        this.writeMessage(this.formatMessage(message));
      }


      public static ClientEvent getEventInstance(String key,HttpServletRequest request,HttpServletResponse response) {          
        return new SampleEvent(key,request.startAsync());
      }

}



      default String formatMessage(String msg) {
        return "data: " + msg +"\n";
      }
  1. Connection seems like synchronous
  2. Message doesnot received at client End



Aucun commentaire:

Enregistrer un commentaire