Matthew Frazier <leafstormrush@gmail.com>
The most common library for networking in Lua is LuaSocket by Diego Nehab. In addition to low-level support for communicating directly through sockets, it also includes:
- HTTP client
- FTP client
- SMTP client
- Mail processing filters
- URL manipulating functions
LuaSocket is installable via LuaRocks, as explained in luarocks
. Many distributions also provide LuaSocket packages.
To create a TCP socket1 connected to a particular place, you can use socket.connect, like this:
require 'socket'
local sock = socket.connect("www.example.com", 80)
From there, you can send and receive on the socket object. :
sock:send("GET / HTTP/1.0\n\n")
local data = sock:recv()
Warning
Don't EVER actually try to handle HTTP like this! Use socket.http
, which we will be covering soon!
You could also use socket.tcp("www.example.com", 80)
and then connect
it separately, but this is a shortcut.
Servers are cool! According to some guy we met:
Servers are the whole reason the Internet exists as we know it.
You can create servers by using socket.bind
.
Here is a graph about servers.
Everyone is talking about concurrency these days!
Story
One day, there was this guy named why the lucky stiff. Unfortunately, before concurrency became popular, he disappeared and no one has heard from him sense. Which is too bad, because he probably would have come up with a good way to do concurrency no one had thought of before.
Some of the ways people have thought of for being concurrent are:
- Multithreading.
- Having multiple processes.
- Asynchronous programming.
Fortunately, Lua has something cool you can use for number three: Coroutines! (If you don't know about coroutines, see using-coroutines
for more info.)
- client
The program run by the user that talks to clients.
- server
The program that clients talk to.
- TCP
What most people use nowadays instead of UDP.
There's also UDP, but we're not covering it in this introduction.↩
Whoops, it was supposed to display the source, not render it. At least there's a "raw" link.