Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- DEBUG = true;
- Sock = TcpSocket.New()
- Sock.EventHandler = print;
- Sock.Data = function()
- local function read()
- return Sock:ReadLine(TcpSocket.EOL.Any);
- end;
- for line in read do
- if(DEBUG) then print('> ' .. line); end;
- -- do something with received data here
- end;
- end;
- -- Helper function for appending EOL & debugging
- Write = function(s)
- if(DEBUG) then print('< ' .. s); end;
- Sock:Write(s .. '\r\n');
- end;
- -- Command sending queue
- SendQueue = {};
- SentCmdLastTick = false;
- SendTimer = Timer.New()
- SendTimer.EventHandler = function()
- local msg = table.remove(SendQueue, 1);
- SentCmdLastTick = msg ~= nil;
- if(msg) then Write(msg); end;
- end; SendTimer:Start(0.25);
- Send = function(...)
- if(not Sock.IsConnected) then error('connection is closed'); end;
- local msg = string.format(...);
- if(SentCmdLastTick) then
- Write(msg); -- send immediately if last timer tick didn't send anything
- else
- table.insert(SendQueue, msg);
- end;
- end;
- -- Example requesting the Google homepage headers
- Sock:Connect('www.google.com', 80);
- Sock.Connected = function()
- for _,m in pairs({
- 'HEAD / HTTP/1.1',
- 'Host: www.google.com',
- '\r\n'
- }) do Send(m); end;
- end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement