Socket and packet

  • The socket userdata You’ll have full access to any networking thing you’d want to do with this.
  • Example HTTP connection
local sock = new Socket()
sock.Connect("google.com", 80)

local p = new Packet()
p.WriteLine("GET / HTTP/1.1")
p.WriteLine("Host: www.google.com")
p.WriteLine("")

sock.Send(p)

while(true){
        p = sock.Receive(1024)

        if (p){
                print(p.ToString())
        }
}
  • Example webserver
local s = new Socket()
s.Host(80)
s.SetBlocking(true)

local filetypes = {
        txt = "text/html",
        html = "text/html",
        css = "text/html",
        gif = "image/gif",
        png = "image/png"
}

while(true){
        local c = s.Accept()

        if (c){
                c.SetBlocking(true)

                local p = c.Receive(100)
                local path = p.ToString()
                path = String.Sub(path, String.IndexOf(path, "/"))
                path = String.Trim(String.Sub(path, 1, String.IndexOf(path, " ")))

                if (path == "")
                        path = "index.html"

                path = "www/" + path
                local ext = "txt"
                if (String.IndexOf(path, ".") > -1)
                        ext = String.Sub(path, String.IndexOf(path, ".") + 1)

                if (!filetypes[ext])
                        ext = "txt"

                print("%:%" % {c.GetIP(), c.GetPort()}, path, ext)

                local file = new IO()
                if (file.Open(path, "rb")){
                        p = new Packet()
                        p.WriteLine("HTTP/1.0 200 OK")
                        p.WriteLine("Date: Fri, 31 Dec 1999 23:59:59 GMT")
                        p.WriteLine("Content-Type: " + filetypes[ext])
                        p.WriteLine("Content-Length: " + file.GetLength())
                        p.WriteLine("")
                        p.WriteBytes(file.ReadToEnd())
                        c.Send(p)
                        file.Close()
                }else{
                        p = new Packet()
                        p.WriteLine("HTTP/1.0 404 FILE NOT FOUND")
                        p.WriteLine("Date: Fri, 31 Dec 1999 23:59:59 GMT")
                        p.WriteLine("Content-Type: text/html")
                        p.WriteLine("Content-Length: 15")
                        p.WriteLine("")
                        p.WriteLine("File not found!")
                        c.Send(p)
                }
        }
}