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) print("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) print(sz) end end
udp = socket.udp() udp:settimeout(0) -- connect to UDP server udp:setpeername("localhost", 14285) udp:send("Hello") function love.keypressed(key, ...) -- send any pressed key to our 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)