0Pricing
Lua Academy · Lesson

Cosockets and Non-Blocking TCP

Use ngx.socket.tcp for async backend connections in content_by_lua.

What Are Cosockets?

OpenResty cosockets are non-blocking TCP/UDP sockets that integrate with Nginx's event loop. When waiting for data, they yield the coroutine, freeing the worker to handle other requests.

Creating a TCP Cosocket

Use ngx.socket.tcp() to create a cosocket. Connect, send, and receive all yield automatically when I/O would block.

-- content_by_lua_block
local sock = ngx.socket.tcp()
local ok, err = sock:connect("redis.local", 6379)
if not ok then
  ngx.log(ngx.ERR, "Connect failed: ", err)
  return ngx.exit(500)
end

All lessons in this course

  1. OpenResty Architecture
  2. Handling HTTP Requests in Lua
  3. Cosockets and Non-Blocking TCP
  4. Shared Memory Dictionaries
← Back to Lua Academy