mod_lua supports basic WebSocket operations such as reading, writing and pinging WebSocket clients with the new 2.4.7 release.
To make a request turn into a WebSocket request, all you have to do is call r:wsupgrade and, if it succeeds, you'll be able to read and write to the client.
Reading and writing are done through WebSocket's full duplex frames, meaning you can interact with your server in a more dynamic way than with plain HTTP. To send a message to your client, use r:wswrite, and to read a message from the client, use r:wsread. You can also perform a ping/pong interaction through r:wsping. mod_lua supports reading masked frames, both binary and text, and sends back unmasked text frames for maximum browser compatibility.
Both the plain text WS protocol and the secure (WSS) protocol is supported by mod_lua.
-- First, try to upgrade the connection to WebSockets: if r:wsupgrade() then -- Then, we'll write something to the client: r:wswrite("Hello, world! Please send me something.") -- Receive a line (frame) from the client: local line = r:wsread() or "nothing" -- Echo that line back to the client r:wswrite("You wrote: " .. line) -- Close up the connection r:wswrite("Goodbye!") r:wsclose() end
function wshandle(r) -- Is this a websocket request? if r:wsupgrade() then -- Greet the client r:wswrite("Hi, this is a websocket calculator, please enter some math, or enter 'exit' to quit: \n") -- Read a math question from client local line, fin = r:wsread() while line do -- Is the client quitting? if line == 'exit' then break end -- Only allow math stuffs line = line:gsub("[^%s0-9%-%%+/*^%(%)]", "") -- Do the math local okay, result = pcall(loadstring("return (" .. line .. ")")) -- Output the result if okay then r:wswrite(line .. " = " .. result) else r:wswrite("Bad math :(") end -- Read a new math question line = r:wsread() end -- Bye bye! r:wswrite("Goodbye!") r:wsclose() return apache2.DONE end return apache2.DECLINED end