webery icon indicating copy to clipboard operation
webery copied to clipboard

SSE (Server Sent Events) Support?

Open ohenepee opened this issue 6 years ago • 4 comments

Is Server Sent Events supported?

ohenepee avatar Sep 18 '18 00:09 ohenepee

There is no dedicated api for it, as SSE is pretty simple protocol you can implement it by yourself, but I would recommend to use WebSockets instead.

If you really need SSE and don't want to implement it, then you need to wait until next snapshot, I will add it

wizzardo avatar Sep 18 '18 09:09 wizzardo

I guess I'll wait then. My reason for opting to use SSE instead of WebSockets is all about memory efficiency... I want to do more (20k+ connections) on my little 1-Core CPU 1GB RAM server, and apparently the HTTP protocol is so old and so mature and so optimized that its possible to do that, but the same can't be said for WebSockets... currently its only uWebSockets (C++) that able to scale that much, but I'm not a C++ dev so I've stayed away.

ohenepee avatar Sep 18 '18 10:09 ohenepee

there is no much difference in case of cpu or memory usage, websockets should be ok, if you need any help to setup it, I can prepare couple of examples

wizzardo avatar Sep 18 '18 10:09 wizzardo

Ok, I've added SSEHandler, not properly tested yet, api might change in the future. Here is a stupid example (do not create thread for each request!):

        HttpServer<?> application = new WebApplication(args);
        application.getUrlMapping()
                .append("/sse", new SSEHandler() {
                    @Override
                    protected void onConnect(Request request) {
                        Thread sender = new Thread(() -> {
                            HttpConnection connection = request.connection();
                            ByteBufferProvider bufferProvider = byteBufferProviderThreadLocal.get();
                            int i = 0;
                            while (connection.isAlive()) {
                                Unchecked.run(() -> Thread.sleep(1000));
                                connection.write(new SSEHandler.SSEEvent(String.valueOf(i++), "date", DateIso8601.format(new Date())).toReadableData(), bufferProvider);
                            }
                        });
                        sender.setDaemon(true);
                        sender.start();
                    }
                })
        ;



    static ThreadLocal<ByteBufferProvider> byteBufferProviderThreadLocal = ThreadLocal.<ByteBufferProvider>withInitial(() -> {
        ByteBufferWrapper wrapper = new ByteBufferWrapper(64 * 1024);
        return () -> wrapper;
    });

wizzardo avatar Sep 19 '18 08:09 wizzardo