服务器发送事件

时间:2019-11-05 06:44:42

标签: java tomcat server-sent-events

我对服务器发送的事件有疑问。 服务器推送的消息未在客户端收到。我很长时间更改了消息格式,但仍然无法正常工作。我正在使用普通支柱2。支柱需要做任何更改吗?

这是我的Java代码

    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. 连接似乎是同步的
  2. 客户端未收到消息

0 个答案:

没有答案