对于comet或sse这种推送技术怎样判断刘浏览器连接已经断开

183 views
Skip to first unread message

Zheng Ping

unread,
Dec 8, 2012, 4:23:38 AM12/8/12
to open...@googlegroups.com

初学openresty,有个问题不解,对于comet或SSE这种服务端向浏览器推送的技术,当浏览器断开连接时我怎样在lua代码中判断呢,我的代码如下:
        location /sse {
            content_by_lua '
                ngx.header["Content-Type"] = "text/event-stream\\n\\n";

                local counter = math.random(1, 10);

                while 1 do
                    if "/sse" ~= ngx.var.request_uri then
                        ngx.log(ngx.CRIT, "exit uri:" .. ngx.var.request_uri);
                        ngx.exit(ngx.HTTP_OK);
                    end

                    local cur_date = os.time();
                    ngx.log(ngx.CRIT, "uri :" .. ngx.var.request_uri);
                    ngx.print("event: ping");
                    ngx.print("data: {\\\"time\\\":\\\"" .. cur_date .. "\\\"}");
                    ngx.print("\\n\\n");
                    counter = counter - 1;

                    if counter == 0 then
                        ngx.print("data: this is a message at time " .. cur_date .. "\\n\\n");
                        counter = math.random(1, 10);
                    end

                    ngx.flush( true );
                    ngx.sleep(1);
                end
            ';
        }
我本来想通过 if "/sse" ~= ngx.var.request_uri then ...end 来判断客户端连接的断开,但是明显这是个错误。
我想问一下:
1.我上面的代码会不会在客户端断开连接的时候一直运行导致内存暴涨?
2.我断开浏览器的连接后,运行kill -HUP xxx来重启nginx,在执行ps查看进程,出现:
zhen      4085  0.0  0.0  31688  2176 ?        Ss   15:20   0:00 nginx: master process openresty -p /home/zhen/works/openresty/tutorial/ -c t01.conf
zhen      4439  0.0  0.0  32112  2256 ?        S    16:12   0:00 nginx: worker process is shutting down                      
zhen      4454  0.0  0.0  32112  1540 ?        S    16:14   0:00 nginx: worker process
我不明白为什么4439这个进程会一直处于shutting down这个状态,而迟迟不能退出呢?
3.对于comet或sse这种涉及到推送的技术,一般有哪些检测客户端是否断开链接的方法?
--
with kind regards

agentzh

unread,
Dec 8, 2012, 3:34:11 PM12/8/12
to open...@googlegroups.com
Hello!

2012/12/8 Zheng Ping:
>
> 初学openresty,有个问题不解,对于comet或SSE这种服务端向浏览器推送的技术,当浏览器断开连接时我怎样在lua代码中判断呢,

请参见 ngx_lua 的文档中关于 lua_check_client_abort 配置指令和 ngx.on_abort() 函数的段落:

http://wiki.nginx.org/HttpLuaModule#lua_check_client_abort
http://wiki.nginx.org/HttpLuaModule#ngx.on_abort

另外,正如上面的文档已经提及的,建议同时启用你的系统的 TCP 协议栈的 TCP keepalive 支持(注意,这里说的不是 HTTP
keepalive!),以及时检测出 half-open 状态的 TCP 连接。

Best regards,
-agentzh

Reply all
Reply to author
Forward
Message has been deleted
0 new messages