#!/usr/bin/env lua5.1
local socket = require("socket")


-- Client definition
local CClient= {}
CClient.__index = CClient


function CClient:new(host, port)
    local client = setmetatable({}, self)
    client.host = host or "127.0.0.1"
    client.port = port or 4222
    client.socket = nil
    client.subscriptions = {}
    return client
end

function CClient:connect()
    self.socket = assert(socket.tcp())
    assert(self.socket:connect(self.host, self.port))
    self.socket:settimeout(0)
    print("Connected to server at " .. self.host .. ":" .. self.port)

    local info = self:read_line()
    if info then
        print("Server INFO: " .. info)
    end
end

function CClient:read_line()
    local line, err = self.socket:receive("*l")
    if err ~= "timeout" then return line end
end

function CClient:send(cmd)
    assert(self.socket:send(cmd .. "\r\n"))
end

function CClient:pub(sub, msg)
    local len = #msg
    local cmd = string.format("PUB %s %d\r\n%s", sub, len, msg)
    self:send(cmd)
end


local client = CClient:new("127.0.0.1", 4222)
client:connect()

local subject = arg[1] or "."
local message = arg[2] or "."
client:pub(subject, message)


