Sockets (Network) Programming
The Socket API provides both blocking sockets and 100% non-blocking sockets. Blocking sockets are suitable when used in combination with LSP pages. The following blocking socket example makes the LSP page wait until a response is returned from the NTP time server. The Lua code executing at the server converts the returned result to a printable format and sends the result to the browser.
The above example is copied from the documentation. See the blocking sockets documentation for an explanation on how this example works.
100% Non-Blocking Sockets
Notice how we use function "trace" and not "print". Function "print" in an LSP page emits data as a response to the browser. We cannot use function "print" in a cosocket since the request/response object, aka the command environment, does not exist in a cosocket.
Function "trace" emits the output to the server's trace buffer. You can also see the printout in the console window if the server is running in console mode. Another option is to view the printout in real time by using the TraceLogger: (1) Open the TraceLogger in a separate browser window and (2) run the above example. You should see the printout in the TraceLogger's console.
Secure Client Socket Example
Creating a secure socket connection is very easy with the socket API. For example, to create a secure TCP client connection, add the attribute "shark" to the options (op) argument for function ba.socket.connect. Attribute "shark" must be set to a SharkSSL object. The Mako Server comes with a ready to use SharkSSL object that is initialized with the most common CA root certificates, and this object is returned by function mako.sharkclient().
The above example connects to google.com at line 16. The port number 443 is the port number used by HTTPS. Attribute "shark" is set to the ready to use Mako Server SharkSSL object.
Line 18 to 20 prints out information related to the secure communication. Function "printTab" takes a table as argument and recursively prints out all the key,value attributes in the table. The function is used to recursively print out the Google server's certificate information.
A basic HTTP request is sent at line 22.
The code enters a loop at line 23 and keeps reading HTTP response data until the read function on line 24 times out.
Secure Server Socket Example
A secure server socket example is included in the BAS API tutorial.
- Start the BAS API tutorial
- Click Tutorials -> Miscellaneous
- Click Miscellaneous -> Sockets API
- Scroll down to "ELIZA the Psychotherapist Web Server"