Advertisement
Guest User

Untitled

a guest
Apr 10th, 2020
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.23 KB | None | 0 0
  1.  
  2. DEBUG = true;
  3.  
  4. Sock = TcpSocket.New()
  5.  
  6. Sock.EventHandler = print;
  7.  
  8. Sock.Data = function()
  9.  
  10.   local function read()
  11.     return Sock:ReadLine(TcpSocket.EOL.Any);
  12.   end;
  13.  
  14.   for line in read do
  15.     if(DEBUG) then print('> ' .. line); end;
  16.     -- do something with received data here
  17.   end;
  18.  
  19. end;
  20.  
  21. -- Helper function for appending EOL & debugging
  22. Write = function(s)
  23.   if(DEBUG) then print('< ' .. s); end;
  24.   Sock:Write(s .. '\r\n');
  25. end;
  26.  
  27. -- Command sending queue
  28. SendQueue = {};
  29. SentCmdLastTick = false;
  30.  
  31. SendTimer = Timer.New()
  32. SendTimer.EventHandler = function()
  33.   local msg = table.remove(SendQueue, 1);
  34.   SentCmdLastTick = msg ~= nil;
  35.   if(msg) then Write(msg); end;
  36. end; SendTimer:Start(0.25);
  37.  
  38. Send = function(...)
  39.   if(not Sock.IsConnected) then error('connection is closed'); end;
  40.   local msg = string.format(...);
  41.   if(SentCmdLastTick) then
  42.     Write(msg); -- send immediately if last timer tick didn't send anything
  43.   else
  44.     table.insert(SendQueue, msg);
  45.   end;
  46. end;
  47.  
  48. -- Example requesting the Google homepage headers
  49. Sock:Connect('www.google.com', 80);
  50. Sock.Connected = function()
  51.   for _,m in pairs({
  52.     'HEAD / HTTP/1.1',
  53.     'Host: www.google.com',
  54.     '\r\n'
  55.   }) do Send(m); end;
  56. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement