--Load the socket library require("socket") --Set version to check with client VERSION = "0.1" --Create our client object listening = socket.tcp() --Set the client to listen assert(listening:bind("127.0.0.1", 2222)) assert(listening:listen()) --Create connections table clients = {} --Add our initial connection to the table table.insert(clients,listening) -- wrap receive() in a yield so that we don't block the program! function niceReceive(sock, ...) coroutine.yield() return sock:receive(...) end -- this coroutine is responsible for dealing with a single client function clientHandler(sock) sock:send("HELLO") sock:send("VERSION "..VERSION) response = sock:receieve("*l") if RESPONSE ~= VERSION then sock:send("BAD VERSION. SERVER: "..VERSION) sock:close() else print("Client connected.") -- read commands from the client and process them while true do local message, err = niceReceive(sock, '*l') print("Got a message: ", message) end end end --Loop forever while true do local reading,writing,err = socket.select(clients,nil) if reading[listening] then local connected = listening:accept() clients[connected] = { sock = connected } -- create new entry in clients table clients[connected].handler = coroutine.create(clientHandler) coroutine.resume(clients[connected].handler, clients[connected].sock) else for socket in pairs(reading) do coroutine.resume(clients[socket].handler) end end end --Parse command from a client. (Got this ready for later) function ParseCommand(command) if command == "HELLO" then return "HELLO" end end