lualuasocket

How to telnet an address?


I'm trying to understand the socket class and i'm using the following example to implement a server sample

local server = assert(socket.bind("*", 0))

-- find out which port the OS chose for us
local ip, port = server:getsockname()

-- print a message informing what's up
print("Please telnet to localhost on IP [" ..ip.. "] and port [" .. port .. "]")
print("After connecting, you have 10s to enter a line to be echoed")

-- loop forever waiting for clients
while true do
-- wait for a connection from any client
local client = server:accept()

-- make sure we don't block waiting for this client's line
client:settimeout(10)

-- receive the line
local line, err = client:receive()

-- if there was no error, send it back to the client
if not err then
    client:send(line .. "\n")
end

-- done with client, close the object
client:close()
end

But now the question is, how can I telnet for example the address localhost:8080 via lua?

EDIT: I forgot to tell something, I don´t even can telnet on cmd. When I type the command:

telnet ip port

it always says "connection lost" after I send a message. What am I doing wrong?


Solution

  • Done!

    local socket = require("socket")
    
    local server = socket.connect(ip, port)
    
    local ok, err = server:send("RETURN\n")
    if (err ~= nil) then
        print (err)
    else
        while true do
            s, status, partial = server:receive(1024)
            print(s or partial)
    
            if (status == "closed") then
                break
            end
        end
    end
    
    server:close()