lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


>   So I'm struggling to understand how to approach implementation
>  I want to allow users to be able to do:
> 	socket = connect( "host", port );
> 	send( socket, "GET / HTTP/1.0\n\n" );
> 	header = read( socket );
> 	data = read( socket );
> 	close( socket );
>   How do other people approach this problem?  (In composing this
>  mail I did a few searchs and see the existance of LuaSocket - this
>  might help me, if I can embed it within my code.  Too soon to tell,
>  but my natural reaction is to think that is overkill ...)

Currently i'm embedding lua as an scripting language in an irc bot
based on the 'energymech'. For scripting purposes i made a 'Socket'
library which uses the bots 'infrastructure' for socket handling.
This socket code doesn't support binary data.

Currently implemented socket-functions for scripts are:

      n = Socket.Connect (s:host, n:port, s:function [, s:vhost])
      n = Socket.Listen (n:port, s:function [, b:perm])
          Socket.Close (n:sockID [, b:flag])
   n, b = Socket.Status (n:sockID)
   b, s = Socket.Write (n:sockID, s:message)
      s = Socket.Read (n:sockID)

to open an incoming (listening) socket you would write:

  lsock = Socket.Listen(40001, "mySockFunc", true);
  if not lsock then [error opening listener] end;

(the 'true' flag keeps the listener socket open, this means every
client which connects will create a new socket id). The function
"mySockFunc" will be called if a client connects, disconnects
or sends data, with three parameters: The sockID, a (message)
string, and a status code:

-- this function will just reply the incoming message
-- back to the sender until we receive 'CIAO':
function mySockFunc(sid, msg, stat)
    if stat < 0 then
    elseif stat > 0 then
    -- stat is 0 here
    if not msg then return end
    Socket.Write(sid, msg) -- send the message back
    if string.upper(msg) == "CIAO" then

so you just can "telnet <host> 40001" and type CIAO to disconnect ;)

If you're interested i can prepare an archive with the documentation
and source code (however, there will be changes to the final version).