This is going to be a very brief introduction to LuaSocket, a generic networking library for Lua. In particular, we will be looking at UDP (User Datagram Protocol). UDP is different than TCP in a number of ways. Generally speaking, UDP is simpler and more lightweight.
In this tutorial, we are going to setup a server and a client script. This will allow us to run two or more instances of the engine and pass messages between them. Before we can do that, we first include the LuaSocket module.
socket = require ( "socket" )
udp = socket.udp ( ) udp:settimeout ( 0 ) -- bind UDP to all local interfaces udp:setsockname ( "*", 14285 ) log_msg ( "Waiting for clients..." ) function update ( ) -- receive incoming data from clients while true do local data, ip, port = udp:receivefrom ( ) if data == nil then break end local sz = string.format ( "Received: %s (%s:%s)", data, ip, port ) log_msg ( sz ) end end timer = Timer ( ) timer:start ( 100, true ) timer.on_tick = function ( timer ) update ( ) redraw_log ( ) end
udp = socket.udp ( ) udp:settimeout ( 0 ) -- connect to UDP server udp:setpeername ( "localhost", 14285 ) udp:send ( "Hello" ) keyboard.on_press = function ( keyboard, key ) -- send the pressed key number to server udp:send ( key ) end
Notice that we have added a callback function that sends a message to the server whenever a keyboard key is pressed. This is just for illustrative purposes and is far from ideal since the client can mash the keys at a rather high rate. Usually, it is best to keep the volume of server and client(s) communication to a minimum.
while true do local data = udp:receive ( ) if data == nil then break end end
Since the server could be communicating with several clients, it's important to note the "sendto" function. It is similar to "send" except that "sendto" requires the explicit IP address and port of the receiving client.
udp:sendto ( data, ip, port )