Как отключить буферизацию на сервере Nginx Server for Server sent - PullRequest
0 голосов
/ 04 апреля 2020

Проблема: Nginx Сервер буферизует отправленные сервером события (SSE).

Настройка: Узел v12.13.1, Nginx 1.16.1, Chrome v80

Сценарий: я пытался отключить буферизацию с помощью proxy_buffering off; и даже добавил "X-Accel-Buffering": "no" на сервере Однако резонансный заголовок nginx все еще буферизует все SSE. если я закрою сервер узла или перезапущу сервер nginx, тогда все сообщения SSE будут доставлены клиенту навалом. Я много пробовал, но не знаю, что мне не хватает.

Nginx Файл конфигурации:


events {
    worker_connections  1024;
}

http {
    include       mime.types;
    sendfile        on;   
    keepalive_timeout  65;

    server {
        listen       4200;
        server_name  localhost;

        location / {    
            proxy_set_header Connection '';
            proxy_http_version 1.1;
            chunked_transfer_encoding off;
            proxy_buffering off;
            proxy_cache off;
            proxy_pass http://localhost:8700;
        }
    }
}

Узловой сервер:

var express = require('express');
var app = express();

var template = 
`<!DOCTYPE html> <html> <body>
    <script type="text/javascript">
        var source = new EventSource("/events/");
        source.onmessage = function(e) {
            document.body.innerHTML += e.data + "<br>";
        };
    </script>
</body> </html>`;

app.get('/', function (req, res) {
    res.send(template); // <- Return the static template above
});

var clientId = 0;
var clients = {}; // <- Keep a map of attached clients

// Called once for each new client. Note, this response is left open!
app.get('/events/', function (req, res) {
    req.socket.setTimeout(Number.MAX_VALUE);
    res.writeHead(200, {
        'Content-Type': 'text/event-stream', // <- Important headers
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'X-Accel-Buffering': 'no'
    });
    res.write('\n');
    (function (clientId) {
        clients[clientId] = res; // <- Add this client to those we consider "attached"
        req.on("close", function () {
            delete clients[clientId]
        }); // <- Remove this client when he disconnects
    })(++clientId)
});

setInterval(function () {
    var msg = Math.random();
    console.log("Clients: " + Object.keys(clients) + " <- " + msg);
    for (clientId in clients) {
        clients[clientId].write("data: " + msg + "\n\n"); // <- Push a message to a single attached client
    };
}, 2000);

app.listen(process.env.PORT || 8700);
...