slact / nchan

Fast, horizontally scalable, multiprocess pub/sub queuing server and proxy for HTTP, long-polling, Websockets and EventSource (SSE), powered by Nginx.
https://nchan.io/
Other
3.01k stars 292 forks source link

Publish on websocket handshake #564

Open metatarz opened 4 years ago

metatarz commented 4 years ago

In my application, clients open up a new websocket connection by simply instantiating it i.e new Websocket(pubEndpoint); whenever they visit my website and close it down when navigating away or simply closing the tab. I use nginx as a reverse proxy to perform additional server-side logic, and nchan's role is to deal with websocket publish events. My question is: Is there a way to make nchan publish when opening/closing a websocket? My nginx configuration file is the following:

 location ~ /pub/(\w+)$ {
        nchan_publisher;
        nchan_channel_id $1;
        nchan_publisher_upstream_request /log;
    }

    location ~ /sub/(\w+)$ {
        nchan_subscriber;
        nchan_channel_id $1;

    }

    location /log {
        proxy_pass http://webapp;
        proxy_set_header X-Original-Host $host;
        proxy_set_header X-Channel-Id $nchan_channel_id;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Connection $http_connection;  
        proxy_set_header Upgrade $http_upgrade;  

    }
ivanovv commented 4 years ago

Is there a way to make nchan publish when opening/closing a websocket?

Not sure I understand what exactly do you mean when you say make nchan publish...

If I'm not mistaken, you want some action to happen on opening/closing a websocket In that case https://nchan.io/#subscriber-presence is what you need.

metatarz commented 4 years ago

Yes, subscriber presence works for me. What would be the equivalent of a 'publisher presence'? In accordance with the docs, nchan_publisher_upstream_request would do the job but as I checked, it does not upstream requests unless a message is published.

ivanovv commented 4 years ago

You have two options:

  1. convert your pub endpoint to pubsub https://nchan.io/#pubsub-endpoint (though I'm not sure whether callbacks work the same way for pubsub as they do for sub
  2. connect to sub endpoint at the same time with connecting to pub endpoint