stream server自动关闭tcp连接,keepalive失效

43 views
Skip to first unread message

Sam Tsai

unread,
Nov 22, 2022, 9:04:14 AM11/22/22
to openresty
I am new here,我想通过nginx stream 和 lua实现一个tcp服务端,收发数据先在content_by_lua_block中简单做了一些逻辑。但是客户端收到请求后,nginx自动发送tcp fin指令将连接关闭了,导致客户端无法复用连接。

nginx stream配置
```nginx
stream {
    lua_socket_keepalive_timeout 10s;
    server {
        listen 12400 so_keepalive=65s;
        proxy_timeout 10m;
        #proxy_requests 100;
        #lua_socket_keepalive_timeout 60s;
        content_by_lua_block {
            local sock = ngx.req.socket(true)
            local s_got = sock:receive()
            ngx.print('server got:'..s_got)
        }
    }
}
```
用telnet模拟发送请求,收到response之后提示连接被远程断开
```console
➜  ~ telnet 11.122.171.152 12400
Trying 11.122.171.152...
Connected to 11.122.171.152.
Escape character is '^]'.
hello
server got:helloConnection closed by foreign host.
```
抓包看了下,nginx发送了tcp fin指令主动断开了连接。
223    15.265932    11.122.171.152    30.197.132.178    TCP    60    12400 → 56478 [FIN, ACK] Seq=14 Ack=5 Win=42496 Len=0

请问在stream中没有upstream server的情况下实现keepalive。

Junlong li

unread,
Nov 22, 2022, 9:19:53 AM11/22/22
to openresty
在content_by_lua_block 中应该用 while 循环

        content_by_lua_block {
            local sock = ngx.req.socket(true)
             while true do
                local local data, err = sock:receiveany(10 * 1024)
                if err then
                    break
                end

                ngx.print('server got:', data)
            end
        }

Sam Tsai

unread,
Nov 24, 2022, 10:51:27 AM11/24/22
to openresty
同步调用sock:receiveany()的worker还能接收并处理其他socket吗?如果我开了8个worker,是不是意味着服务端只能处理8个socket?

Sam Tsai

unread,
Nov 24, 2022, 11:49:02 AM11/24/22
to openresty
看了这个文档(http://www.aosabook.org/en/nginx.html)似乎找到了答案。worker通过run-loop实现了非常高效的异步处理连接事件的机制。
Reply all
Reply to author
Forward
0 new messages