Lua http socket timeout

The documentation for the LuaSocket HTTP module says that a timeout can be set in an HTTP connection:

To control the behavior of the HTTP module, the following constants can be set by default:

PORT: default port used for connections; PROXY: the default proxy server used for connections; TIMEOUT: sets a timeout for all I / O operations; USERAGENT: The default user agent tells the server. http://w3.impa.br/~diego/software/luasocket/http.htm

How to set these constants in lua script?

+7
source share
2 answers

You can do this to set a timeout for a single request instead of the entire HTTP module:

local socket = require "socket" local http = require "socket.http" response = http.request{url=URL, create=function() local req_sock = socket.tcp() req_sock:settimeout(5) return req_sock end} 

Note that the default behavior :settimeout by default, as well as global parameters such as http.TIMEOUT , sets the time limit for any single operation in the request - in other words, how long the operation can go without any activity before calculating the time. If you want to set the general upper bound of the operation — the time when the general request cannot exceed, regardless of activity — you must pass the mode argument 't' as the second parameter to :settimeout , for example:

 local socket = require "socket" local http = require "socket.http" response = http.request{url=URL, create=function() local req_sock = socket.tcp() -- note the second parameter here req_sock:settimeout(5, 't') return req_sock end} 

As an example, to illustrate the difference between the two modes, imagine that after executing your request, the server responded with a response block once per second, completing seven seconds in total. With req_sock:settimeout(5, 'b') (or just req_sock:settimeout(5) ) setting a 5 second block timeout, this query will work very well, since none of the I / O operations took longer five seconds: however, req_sock:settimeout(5, 't') set five - the total general timeout, the request will fail after five seconds.

Of course, it makes sense to set limits for both of these durations, having both a short inactivity timeout and a longer overall timeout. So in the documentation , you can make two separate calls to indicate both:

 local socket = require "socket" local http = require "socket.http" response = http.request{url=URL, create=function() local req_sock = socket.tcp() req_sock:settimeout(5, 'b') req_sock:settimeout(30, 't') return req_sock end} 
+6
source

It was easier than I thought. just

 local mysocket = require("socket.http") mysocket.TIMEOUT = 5 
+12
source

All Articles