Hi all,

The background is that I want to use Lanes with Luasocket, and found
that I needed one little patch to do the job. The issue with Lanes is
that one cannot pass userdata to a lane, because it has to copy all
parameters across to the new Lua state, and does not know the intended
copy semantics of any piece of userdata.  However, s:getfd() _and_
s:getfd() exist for sockets, although not documented, since it breaks
encapsulation and no doubt leads to trouble somewhere.  We can pass
handles (as numbers that can pass as Lua numbers) to a Lane, and the
patch adds socket.client(fd) which is given a previously prepared
socket handle and makes us a client socket.

Then this multi-threaded version of the listener example becomes possible:

local socket = require("socket")
local lanes = require 'lanes'
host = host or "*"
port = port or 8080
if arg then
        host = arg[1] or host
        port = arg[2] or port
end

function client_handler(fd)
    local socket = require 'socket'
    local c = socket.client(fd)  --> new function!
    local l, e = c:receive()
    while not e do
        print(l)
        l, e = c:receive()
    end
    print(e)
end

print("Binding to host '" ..host.. "' and port " ..port.. "...")
s = assert(socket.bind(host, port))
while true do
    print("Waiting connection from talker")
    c = assert(s:accept())
    print("Connected. Here is the stuff:")

    lanes.gen('*',client_handler)(c:getfd())
end

The definition of socket.client is straightforward:

static int global_client(lua_State *L)
{
    t_socket sock = lua_tonumber(L,1);
    p_tcp clnt = (p_tcp) lua_newuserdata(L, sizeof(t_tcp));
    auxiliar_setclass(L, "tcp{client}", -1);
    /* initialize structure fields */
    socket_setnonblocking(&sock);
    clnt->sock = sock;
    io_init(&clnt->io, (p_send) socket_send, (p_recv) socket_recv,
            (p_error) socket_ioerror, &clnt->sock);
    timeout_init(&clnt->tm, -1, -1);
    buffer_init(&clnt->buf, &clnt->io, &clnt->tm);
    return 1;
}

Naturally, I'm not the first to suggest such a hack. Also look at:

http://www.net-core.org/

steve d.

PS. Also, this is not a request for including such a patch, but
something to stimulate discussion about more well-thought-out
modifications.

_______________________________________________
Kepler-Project mailing list
Kepler-Project@lists.luaforge.net
http://lists.luaforge.net/cgi-bin/mailman/listinfo/kepler-project
http://www.keplerproject.org/

Reply via email to