Lua
Lua
Socket Receive String Until Specific Byte Value is Received
Demonstrates the Chilkat Socket ReceiveStringUntilByte method.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
local sock = chilkat.Socket.new()
-- --------------------------------------------------------------------
-- This example uses the public TCP echo service at https://tcpbin.com/
-- --------------------------------------------------------------------
local useTls = false
local port = 4242
local maxWaitMs = 5000
local success = sock:connect("tcpbin.com", port, useTls, maxWaitMs)
if not success then
print(sock.last_error_text)
return
end
-- Wait a max of 2 seconds for a response..
sock.max_read_idle_ms = 2000
-- Send some strings, each terminated by a 0 byte.
sock:send_string("This is the 1st string")
sock:send_byte(0)
sock:send_string("This is string number 2")
sock:send_byte(0)
-- The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
sock:send_byte(10)
-- Now let's receive what is echoed back....
-- Receive each string and the NULL byte.
-- The call to ReceiveStringUntilByte will receive incoming data until the lookForByte is encountered.
-- The lookForByte is receive and discarded (it is not returned in the string)
local lookForByte = 0
local s1 = sock:receive_string_until_byte(lookForByte)
if not sock.last_method_success then
print(sock.last_error_text)
return
end
print(s1)
local s2 = sock:receive_string_until_byte(lookForByte)
if not sock.last_method_success then
print(sock.last_error_text)
return
end
print(s2)
-- The echo server will also echo back the final LF
sock:receive_byte(true)
maxWaitMs = 100
sock:close(100)
-- Output:
-- This is the 1st string
-- This is string number 2