This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm that you accept these cookies being set.

TCP/ip connect and maintain connection
#2
Use this resident script (sleep time = 0) as a starting point:
Code:
-- socket connected
if connected then
  -- send command
  sock:send('CS 1 65535\r')

  -- read until one line received or error occured
  while true do
    char, err = sock:receive(1)

    -- error while receiving, timeout or closed socket
    if err then
      -- remote server closed connection, reconnect
      if err == 'closed' then
        connected = false
        alert('[tcp-sock] connection closed')
        os.sleep(1)
      end

      break
    -- end of line, parse buffer
    elseif char == '\r' then
      data = table.concat(buffer)
      log(data)
      buffer = {}

      -- wait some time before next request
      os.sleep(1)

      break
    -- other char, add to buffer
    else
      buffer[ #buffer + 1 ] = char
    end
  end
-- first call or previously disconnected
else
  -- close previous connection when disconnected
  if sock then
    sock:close()
    sock = nil
  end

  -- create tcp socket
  sock = require('socket').tcp()
  sock:settimeout(1)
  connected, err = sock:connect('192.168.0.9', 80)

  -- connect ok, reset buffer
  if connected then
    alert('[tcp-sock] connection ok')
    buffer = {}
  -- error while connecting
  else
    alert('[tcp-sock] connection failed: %s', err)
    os.sleep(5)
  end
end
Reply


Messages In This Thread
RE: TCP/ip connect and maintain connection - by admin - 19.10.2023, 06:48

Forum Jump: