Created
April 18, 2023 19:45
-
-
Save madmaxoft/e54464846e0ab04fef00726caaa7a0d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Main.lua | |
--[[ | |
Starts a TCP server; then launches self again with the server port as param, which creates a client that connects to the server. | |
The server uses socket timeouts to report time, the client doesn't send any response to trigger the timeout. | |
In ZeroBraneStudio on Linux, the :settimeout() call seems to succeed, but the timeout is ignored and pretty much | |
every :receive() call then returns immediately with a "timeout" error. | |
--]] | |
local socket = require("socket") | |
local args = arg or {...} | |
-- Outputs the specified text with a prepended timestamp | |
local function log(aText) | |
assert(type(aText) == "string") | |
local d = os.date("%H:%M:%S") | |
print(d, aText) | |
end | |
-- Runs the server process part: | |
local function doServer(aSelfFileName) | |
assert(type(aSelfFileName) == "string") | |
local port = 32000 | |
local server = assert(socket.bind("localhost", port, 0)) | |
log("S: Listening on port " .. tostring(port)) | |
-- while (true) do | |
do | |
-- Launch the client process: | |
local childProcess = io.popen("lua " .. aSelfFileName .. " " .. tostring(port), "w") | |
-- Accept the client: | |
local client = assert(server:accept()) | |
log("S: Client connected: " .. tostring(client:getpeername())) | |
-- Wait for 10 consecutive (timeouting) reads from the client, log each one with timestamp: | |
client:settimeout(1) | |
for i = 1, 10 do | |
local data, msg = client:receive(1) | |
if not(data) then | |
log("S: Failed to receive client data: " .. tostring(msg)) | |
end | |
client:send('a') | |
end | |
client:close() | |
childProcess:close() | |
end | |
end | |
-- Runs the client process part: | |
local function doClient(aPort) | |
assert(type(aPort) == "number") | |
log("Client: Connecting to port " .. tostring(aPort)) | |
local client = assert(socket.connect("localhost", aPort)) | |
print(client:receive("100")) | |
end | |
-- Main: | |
if (args[1]) then | |
doClient(tonumber(args[1])) | |
else | |
doServer(args[0]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment