TCP server sample

Following post provides a TCP server listening on IP 192.168.14.31 (USB IP of the Airlink device), port 56789.

In case you want to access the TCP server from the WAN interface, you must in AceManager set a port forwarding rule. In Security tab, Port Forwarding menu, set the host IP and port to the IP and port specified in the socket.bind API



local sched  = require "sched"  -- Lua scheduling and synchronization lib. 
								-- Beware to call it before the socket lib otherwise socket will not connect 
local socket = require "socket"


function main ()
	local server = assert(socket.bind("192.168.14.31", 56789))

	print("inside main")

	while true 
	do
		-- wait for a connection from any client
		local client = server:accept()
		-- make sure we don't block waiting for this client's line
		client:settimeout(10)

		while true do
			-- receive the line
			-- there are 3 methods to receive data: 
			-- "*l", to receive line by line (beware that the client must send the line feed character! if you are using a TCP client tool, do check the "LineFeed" box if any)
			-- n, to specify a number of bytes to read out from the socket
			-- "*a", to read all the data on the fly  
			local line, err = client:receive("*l")
			-- if there was no error, send it back to the client
			if not err then 
				print("received data:", line)
				-- client:send(line .. "\n") end
				client:send("this is the answer from my AAF TCP server") 
			else print(err)
				if err == "closed" then 
					client:close()
					break
				end
			end
		end

	end

end

--------------------------------------------------------------------------------
-- Schedule the main function, and launch the scheduler main loop
sched.run(main)
sched.loop()

Hi ,
Thank you for sharing information :slight_smile:

-Alex