Receive and send data over TCP communication with LM
Example: Receive and send data over TCP communication with LM
One of possibilities how to exchange the data with external servers is by using TCP requests.
Logic Machine as a client
- The following program will connect to IP address 192.168.1.1 port 12345, send ‘1234567890’:
- -- init socket
- if not sock then
- require('socket')
-
- sock, err = socket.connect('192.168.1.1', 12345)
-
- -- set timeout to 1 second
- if sock then
- sock:settimeout(1)
- -- error opening connection, log error and wait before reconnecting
- else
- error(err)
- sleep(5)
- end
- end
-
- -- socket handler
- if sock then
- -- send data to socket
- sock:send('1234567890')
-
- -- get 10 bytes of data from socket or wait for timeout
- data = sock:receive(10)
- -- got data, log it
- if data then
- log(data)
- end
- end
Logic Machine as a server
- LM can handle multiple TCP connections on the same port. A handler function should be defined which will be called for each connection established.
- Broken connections can be traced using keep-alive packets (enabled using single function call). If connection is broken then usually you just have to close the connection and exit the handler functions.
- Handler example:
- -- server init
- if no server then
- -- handler function
- function handler(sock)
- -- enable keep-alive check
- sock:setoption('keepalive', true)
-
- local ip, port = sock:getpeername()
- alert('connection from ' .. ip .. ':' .. port)
-
- -- main reader loop
- while true do
- -- wait for 10 bytes of data
- local data, err = copas.receive(sock, 10)
-
- -- error, stop handler for this connection
- if err then
- list[ meta.id ] = nil
- return
- end
-
- -- do something with data and send reply to socket
- result = dosomething(data)
- copas.send(sock, result)
- end
- end
-
- require('copas')
- -- bind on port 12345
- server, err = socket.bind('*', 12345)
-
- -- cannot bind to port, wait and return error
- if not server then
- sleep(5)
- error(err)
- end
-
- copas.addserver(server, handler)
- end
-
- -- handle communication for 1 second
- copas.step(1)