Sample Lua Client Application

Lua on Windows supports sockets through the Lua sockets library, use 'require "socket"' or 'require "luasocket"' to activate. This example is the full program from which snippets have been taken as examples in the Sockets Programming Tutorial. The application connects to a web server and uses the HTTP 1.0 protocol to request the root page of the web site.

Sockets
Contents
Contents
Sockets
Examples
Prev

 

The Code


--[[ 
    Simple Lua TCP client 
--]]
   require "socket"
   
   host = "localhost";
   port = 80;
   data = "GET / HTTP/1.0\r\n\r\n";
   
   local count = 0;
   local client, cstat = nil, emsg;
   
 -- basis of assert( socket.connect( host, port));
   clnt, emsg = socket.tcp();
   if ( not clnt) then
      print( "Unable to create TCP object: " .. emsg);
   else
      cstat, emsg = clnt:connect( host, port);
      if ( not cstat) then
         print( "Unable to connect to host " .. host 
                  .. ", port " .. port .. ": " .. emsg);
      end;
   end;
 -- end of assert( socket.connect( host, port));
   
   if ( cstat) then
      local olen = string.len( data);
      local tlen = 0;
      while ( tlen < olen) do
         count, emsg, ecnt = clnt:send( data);
         if ( count == nil) then
            print( "Send to " .. host .. "failed: "
                     .. emsg);
            cstat = nil;
            break;
         end;
         tlen = tlen + count;
         if ( tlen < olen) then
            print( "Partial send, " .. tlen .. " of "
                        .. olen .. " bytes sent");
         end;
      end;
   end;
 
   while ( cstat) do
      local s, status = clnt:receive(4096);
      if ( status ~= "closed" ) then
         print( s);
      else
         cstat = nil; 
      end
   end;
   clnt:close();
   print( "Finished");