| 1 |
-------------------------------------------------------------------------------- |
|---|
| 2 |
-- Title: SocketReader.lua |
|---|
| 3 |
-- Description: Like a square peg in a round hole |
|---|
| 4 |
-- Author: Raphaël Szwarc http://alt.textdrive.com/lua/ |
|---|
| 5 |
-- Creation Date: February 1, 2005 |
|---|
| 6 |
-- Legal: Copyright (C) 2005 Raphaël Szwarc |
|---|
| 7 |
-------------------------------------------------------------------------------- |
|---|
| 8 |
|
|---|
| 9 |
-- import dependencies |
|---|
| 10 |
local LUObject = require( "LUObject" ) |
|---|
| 11 |
local LUTask = require( "LUTask" ) |
|---|
| 12 |
local os = require( "os" ) |
|---|
| 13 |
|
|---|
| 14 |
-- define the class |
|---|
| 15 |
local super = LUObject |
|---|
| 16 |
local self = super() |
|---|
| 17 |
|
|---|
| 18 |
-- constant(s) |
|---|
| 19 |
local Timeout = 60 |
|---|
| 20 |
|
|---|
| 21 |
-- initialization method |
|---|
| 22 |
function self:init( aSocket ) |
|---|
| 23 |
self = super.init( self ) |
|---|
| 24 |
|
|---|
| 25 |
self._socket = aSocket |
|---|
| 26 |
self._status = "timeout" |
|---|
| 27 |
|
|---|
| 28 |
return self |
|---|
| 29 |
end |
|---|
| 30 |
|
|---|
| 31 |
-- method to access this reader socket |
|---|
| 32 |
function self:socket() |
|---|
| 33 |
return self._socket |
|---|
| 34 |
end |
|---|
| 35 |
|
|---|
| 36 |
-- method to close this socket |
|---|
| 37 |
function self:close() |
|---|
| 38 |
self._status = "closed" |
|---|
| 39 |
|
|---|
| 40 |
return self:socket():close() |
|---|
| 41 |
end |
|---|
| 42 |
|
|---|
| 43 |
-- method to read a value |
|---|
| 44 |
function self:read( aPattern, aTimeout ) |
|---|
| 45 |
local aTime = os.time() |
|---|
| 46 |
local aValue, aStatus, aPartialValue = nil |
|---|
| 47 |
|
|---|
| 48 |
aPattern = aPattern or "*l" |
|---|
| 49 |
aTimeout = aTimeout or Timeout |
|---|
| 50 |
|
|---|
| 51 |
while true do |
|---|
| 52 |
aValue, aStatus, aPartialValue = self:socket():receive( aPattern, aPartialValue ) |
|---|
| 53 |
|
|---|
| 54 |
self._status = aStatus |
|---|
| 55 |
|
|---|
| 56 |
if aValue ~= nil or aStatus ~= "timeout" then |
|---|
| 57 |
return aValue, aStatus |
|---|
| 58 |
end |
|---|
| 59 |
|
|---|
| 60 |
if aStatus == "timeout" then |
|---|
| 61 |
if os.difftime( os.time(), aTime ) >= aTimeout then |
|---|
| 62 |
return nil, aStatus |
|---|
| 63 |
end |
|---|
| 64 |
else |
|---|
| 65 |
aTime = os.time() |
|---|
| 66 |
end |
|---|
| 67 |
|
|---|
| 68 |
LUTask:yield( "reader" ) |
|---|
| 69 |
end |
|---|
| 70 |
|
|---|
| 71 |
return nil, aStatus |
|---|
| 72 |
end |
|---|
| 73 |
|
|---|
| 74 |
-- method to access this reader status |
|---|
| 75 |
function self:status() |
|---|
| 76 |
return self._status |
|---|
| 77 |
end |
|---|
| 78 |
|
|---|
| 79 |
return self |
|---|