Advertisement
shadowkat1010

ocsocket.lua

Jun 23rd, 2014
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local component = require "component"
  2. local event = require "event"
  3.  
  4. local socket = {}
  5.  
  6. local octcp = {}
  7.  
  8. octcp.modem = component.modem
  9. octcp.address = ""
  10. octcp.port = 0
  11. octcp.buffer = ""
  12. octcp.psize = 8192
  13.  
  14. function octcp.listen(_,_,from,port,_,message)
  15.  if from == octcp.address and port == octcp.port then
  16.   octcp.buffer = octcp.buffer..message
  17.  end
  18. end
  19.  
  20. function octcp.rawread(n)
  21.  local s = octcp.buffer:sub(1,n)
  22.  if octcp.buffer:len() >= n then
  23.   octcp.buffer=octcp.buffer:sub(n+1)
  24.  else
  25.   octcp.buffer=""
  26.  end
  27.  return s,n
  28. end
  29.  
  30. function octcp.read(i)
  31.  if type(i) == "string" then
  32.   f=octcp.buffer:find(i)
  33.  elseif type(i) == "number" then
  34.   f=i
  35.  else
  36.   f=nil
  37.  end
  38.  if f ~= nil then
  39.   return octcp.rawread(f)
  40.  else
  41.   return nil
  42.  end
  43. end
  44.  
  45. function octcp.write(s)
  46.  local t = {}
  47.  if s:len() > octcp.psize then
  48.   repeat
  49.    octcp.modem.send(octcp.address,octcp.port,s:sub(1,octcp.psize))
  50.    s=s:sub(octcp.psize+1)
  51.   until s:len() <= octcp.psize
  52.  else
  53.   octcp.modem.send(octcp.address,octcp.port,s)
  54.  end
  55. end
  56.  
  57. function octcp.isData()
  58.  if octcp.buffer~="" then return true else return false end
  59. end
  60.  
  61. function octcp.init()
  62.  event.listen("modem_message",octcp.listen)
  63. end
  64.  
  65. function octcp.close()
  66.  event.ignore("modem_message",octcp.listen)
  67. end
  68.  
  69. function socket.socket(port,address)
  70.  t=octcp
  71.  t.address = address
  72.  t.port = port
  73.  return t
  74. end
  75.  
  76. return socket
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement