Cheers @reneboer
I couldn’t seen anything within the Dutch plugin that was specific to Lua sockets, did you? Either way, I worked ok this last night and while there were a few options, I’ve got this running on my Rasp Pi at the moment, listening for anything incoming
-- A Lua listening TCP server
local socket = require 'socket'
local server = socket.tcp()
server:bind('*',51425)
server:listen(32)
local ip, port = server:getsockname()
local localip, _ = socket.dns.toip(socket.dns.gethostname()) -- want host IP, not 127.0.0.1??
print("This is the IP and port to commect to " .. ip ..":".. port)
print("Below is what's being received by the server....")
while 1 do
local client = server:accept()
client:settimeout(20)
print(client:getpeername()) -- shows IP and port
print("Connecting client = " ..client:getpeername()) -- only shows IP, no port, why ???
local line, err = client:receive()
if not err then client:send(line .. "\n") end
print("Client's message = " ..line)
client:close()
end
And now the other client part…
-- A Lua TCP client
local host, port = "192.168.102.37", 41565
local socket = require("socket")
local tcp = assert(socket.tcp())
tcp:connect(host, port);
tcp:send("hello the world\n");
while true do
local s, status, partial = tcp:receive()
print(s or partial)
print(status)
if status == "closed" then break end
end
tcp:close()
My Lua listening server reports the following…
pi@raspberrypi:/ $ lua /home/pi/Documents/listen_vera_server.lua
This is the IP and port to commect to 0.0.0.0:57673
Below is what's being received by the server....
192.168.102.107 49478 inet
Connecting client = 192.168.102.107
Client's message = hello the world
Now for my questions/ challenges / next steps with the above (so far)
.
-
I tried to set this up so the server always use the same port, but every time I stop it from running (CTRL+Z) and then run it again, it gives me a new port no.? Now, Is that due to the port not being closed and it has to open another one instead ? If so is there a cleaner way to stop/restart?
-
It seems I have to put a \n (new line) at the end of any string I send via the client, otherwise it times out. It can send a json like this "tcp:send(’{“type”: “Event”, “userId”: 0, “userName”: “Joe”, “roomName”: “Living Room”, “sensorId”: “98072D0B9B71”, “event”: {“name”: “RoomEntry”, “inControl”: true}}\n’)
-
As this TCP server will needs to be able to receive Http posts from another server, i’m not sure how the server will needs to change to accommodate that … ?