socket.lua (685B)
1 local socket_api 2 local data_callbacks = { } 3 4 local function connect( addr, port, cb ) 5 local sock, err = socket_api.connect( addr, port ) 6 if not sock then 7 return nil, err 8 end 9 data_callbacks[ sock ] = cb 10 return sock 11 end 12 13 local function close( sock ) 14 socket_api.close( sock ) 15 data_callbacks[ sock ] = nil 16 end 17 18 local function on_socket_data( sock, data ) 19 -- data could be like { type = "data/failed/close/etc", data = ... } 20 -- need a failed to handle async connect 21 data_callbacks[ sock ]( sock, data ) 22 end 23 24 return { 25 init = function( api ) 26 socket_api = api 27 28 socket = { 29 connect = connect, 30 send = socket_api.send, 31 close = close, 32 } 33 34 return on_socket_data 35 end, 36 }