感谢回复,下面是我的demo
nginx.conf文件
worker_processes 1;
events {
worker_connections 512;
}
http {
server {
listen 81;
server_name *.*;
location ~ ^/(\w+) {
content_by_lua_file service/backend/$1.lua;
}
location / {
content_by_lua_block {
ngx.say("hello openresty backend")
}
}
}
}
stream {
server {
listen 900;
content_by_lua_file service/stream/cosocket.lua;
}
}
service/backend/cosocket.lua文件
local sock = ngx.socket.tcp()
sock:settimeout(3000)
local ok, err = sock:connect("127.0.0.1", 900)
if not ok then
ngx.say("failed to connect to backend: ", err)
return
end
local count, err = sock:getreusedtimes()
ngx.say("sock usedtimes = ", count)
local data, err = sock:receive("*a")
if not data or err then
ngx.log(ngx.ERR, "recieve data from backend failed: ", err)
return
end
ngx.say("receive from backend: ", data)
ngx.log(ngx.ERR, "test in client")
local ok, err = sock:setkeepalive()
if err then
ngx.log(ngx.ERR, "setkeepalive failed: ", err)
elseif ok then
ngx.log(ngx.ERR, "setkeepalive success")
end
service/stream/cosocket.lua文件
local sock = ngx.req.socket()
local bytes, err = sock:send("test")
if err then
ngx.say("failed to send data to client: ", err)
return
end
ngx.log(ngx.ERR, "test in server")
我运行curl 127.1:81/cosocket
命令得到的输出是:
sock usedtimes = 0
receive from backend: test
我在service/backend/cosocket.lua文件中执行了setkeepalive方法,期望的是多次执行curl
curl命令usedtimes的值会相应的增加,但是结果是始终为0,我查看日志,setkeepalive方法返回的error
error信息是invalid connection,不明白是什么导致的这个错误。