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

Source code    
  1. -- init socket
  2. if not sock then
  3. require('socket')
  4.  
  5. sock, err = socket.connect('192.168.1.1', 12345)
  6.  
  7. -- set timeout to 1 second
  8. if sock then
  9. sock:settimeout(1)
  10. -- error opening connection, log error and wait before reconnecting
  11. else
  12. error(err)
  13. sleep(5)
  14. end
  15. end
  16.  
  17. -- socket handler
  18. if sock then
  19. -- send data to socket
  20. sock:send('1234567890')
  21.  
  22. -- get 10 bytes of data from socket or wait for timeout
  23. data = sock:receive(10)
  24. -- got data, log it
  25. if data then
  26. log(data)
  27. end
  28. 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:
Source code    
  1. -- server init
  2. if no server then
  3. -- handler function
  4. function handler(sock)
  5. -- enable keep-alive check
  6. sock:setoption('keepalive', true)
  7.  
  8. local ip, port = sock:getpeername()
  9. alert('connection from ' .. ip .. ':' .. port)
  10.  
  11. -- main reader loop
  12. while true do
  13. -- wait for 10 bytes of data
  14. local data, err = copas.receive(sock, 10)
  15.  
  16. -- error, stop handler for this connection
  17. if err then
  18. list[ meta.id ] = nil
  19. return
  20. end
  21.  
  22. -- do something with data and send reply to socket
  23. result = dosomething(data)
  24. copas.send(sock, result)
  25. end
  26. end
  27.  
  28. require('copas')
  29. -- bind on port 12345
  30. server, err = socket.bind('*', 12345)
  31.  
  32. -- cannot bind to port, wait and return error
  33. if not server then
  34. sleep(5)
  35. error(err)
  36. end
  37.  
  38. copas.addserver(server, handler)
  39. end
  40.  
  41. -- handle communication for 1 second
  42. copas.step(1)