Advertisement
Techokami

telnet.lua

Jun 12th, 2014
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.98 KB | None | 0 0
  1. local component = require("component")
  2. local internet = require("internet")
  3. local term = require("term")
  4. local text = require("text")
  5. local event = require("event")
  6. local shell = require("shell")
  7.  
  8. if not component.isAvailable("internet") then
  9.   io.stderr:write("telnet requires an Internet Card to run!\n")
  10.   return
  11. end
  12.  
  13. local args, options = shell.parse(...)
  14. if #args < 1 then
  15.   print("Usage: telnet <server:port>")
  16.   return
  17. end
  18.  
  19. local host = args[1]
  20.  
  21. local gpu = component.gpu
  22. local w, h = gpu.getResolution()
  23.  
  24. local hist = {}
  25.  
  26. local sock, reason = internet.open(host)
  27. if not sock then
  28.   io.stderr:write(reason .. "\n")
  29.   return
  30. end
  31.  
  32. sock:setTimeout(0.05)
  33.  
  34. --Function from the built in IRC program
  35. local function print(message, overwrite)
  36.   local w, h = component.gpu.getResolution()
  37.   local line
  38.   repeat
  39.     line, message = text.wrap(text.trim(message), w, w)
  40.     if not overwrite then
  41.       component.gpu.copy(1, 1, w, h - 1, 0, -1)
  42.     end
  43.     overwrite = false
  44.     component.gpu.fill(1, h - 1, w, 1, " ")
  45.     component.gpu.set(1, h - 1, line)
  46.   until not message or message == ""
  47. end
  48. local function draw()
  49.   if not sock then
  50.     return false
  51.   end
  52.   repeat
  53.     local ok, line = pcall(sock.read, sock)
  54.     if ok then
  55.       if not line then
  56.         print("Connection lost.")
  57.         sock:flush()
  58.         sock:close()
  59.         sock:flush()
  60.         sock = nil
  61.         os.exit()
  62.         return false
  63.       end
  64.       print(line)
  65.     end
  66.   until not ok
  67. end
  68. local function uin()
  69.   term.setCursor(1,h)
  70.   line = term.read(hist)
  71.   line2 = text.trim(line)
  72.   if line2 == "/exit" then
  73.     return false
  74.   elseif sock == nil then
  75.     return false
  76.   else
  77.     sock:write(line2.."\r\n")
  78.   end
  79.   return true
  80. end
  81.  
  82. local going = true
  83. local dLoop = event.timer(0.5, draw, math.huge)
  84.  
  85. repeat
  86.   r = uin()
  87. until not r
  88.  
  89. if dLoop then
  90.   event.cancel(dLoop)
  91. end
  92.  
  93. if sock then
  94.   sock:write("QUIT\r\n")
  95.   sock:flush()
  96.   sock:close()
  97.   sock:flush()
  98. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement