Sample code for 30+ languages & platforms
Lua

Socket Send and Receive BinData

Demonstrates the Chilkat Socket ReceiveBdN and SendBd methods.

Chilkat Lua Downloads

Lua
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 26 bytes contained in a Chilkat BinData
local bdToSend = chilkat.BinData.new()
local i = 0
local byteVal = 65
while i < 26 do
    bdToSend:append_byte(byteVal)
    byteVal = byteVal + 1
    i = i + 1
end

-- Send the contents of the BinData
-- Pass zero's in the 2nd and 3rd arguments to send the entire contents of the BinData.
sock:send_bd(bdToSend, 0, 0)

-- The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
sock:send_byte(10)

-- The echo server will echo back whatever is sent to it.
-- We should be able to read the same bytes back..
local bdRecv = chilkat.BinData.new()
-- Receive the 26 bytes previously sent, plus the LF char.
success = sock:receive_bd_n(27, bdRecv)
if not success then
    print(sock.last_error_text)
    return
end

-- Show the contents of bdRecv in hex format
print(bdRecv:get_encoded("hex"))

-- Output:  4142434445464748494A4B4C4D4E4F505152535455565758595A0A