1 %%% Copyright (c) 2007- Facebook
2 %%% Distributed under the Thrift Software License
4 %%% See accompanying file LICENSE or visit the Thrift site at:
5 %%% http://developers.facebook.com/thrift/
11 -include("thrift.hrl").
12 -include("transport/tTransportException.hrl").
13 -include("transport/tSocket.hrl").
17 -export([attr
/4, super
/0, inspect
/1]).
19 -export([new
/0, new
/1, new
/2,
20 effectful_setHandle
/2, effectful_open
/1,
21 isOpen
/1, effectful_write
/2, read
/2, effectful_close
/1]).
25 %%% 'super' is required unless ?MODULE is a base class
34 %%% behavior callbacks
37 %%% super() -> SuperModule = atom()
43 %%% inspect(This) -> string()
46 ?
FORMAT_ATTR(host
) ++ ", " ++
47 ?
FORMAT_ATTR(port
) ++ ", " ++
55 Super
= (super()):new(),
56 #?MODULE
{super
=Super
, host
=Host
, port
=Port
, handle
=nil
}.
62 new("localhost", 9090).
68 effectful_setHandle(This
, Handle
) ->
69 {ok
, oop:set(This
, handle
, Handle
)}.
71 effectful_open(This
) ->
72 Host
= oop:get(This
, host
),
73 Port
= oop:get(This
, port
),
74 Options
= [binary, {packet
, 0}, {active
, false
}],
76 case gen_tcp:connect(Host
, Port
, Options
) of
78 exit(tTransportException:new(
79 ?tTransportException_NOT_OPEN
,
80 "Could not connect to " ++ Host
++ ":" ++ Port
)
83 effectful_setHandle(This
, Socket
)
87 oop:get(This
, handle
) /= nil
.
89 effectful_write(This
, Str
) ->
90 Handle
= oop:get(This
, handle
),
91 Val
= gen_tcp:send(Handle
, Str
),
94 %% error_logger:info_msg("tSocket: wrote ~p~n", [Str]),
96 %% error_logger:info_msg("WRITE |~p| (~p)", [Str,Val]),
100 throw(tTransportException:new(?tTransportException_NOT_OPEN
, "in write"));
106 Handle
= oop:get(This
, handle
),
107 case gen_tcp:recv(Handle
, Sz
) of
109 Host
= oop:get(This
, host
),
110 Port
= oop:get(This
, port
),
111 throw(tTransportException:new(?tTransportException_UNKNOWN
, "TSocket: Could not read " ++ Sz
++ "bytes from " ++ Host
++ ":" ++ Port
));
114 ?
INFO("tSocket: read ~p", [Data
]),
117 exit(tTransportException:new(?tTransportException_NOT_OPEN
, "in tSocket:read/2: gen_tcp:recv"))
120 effectful_close(This
) ->
121 case oop:get(This
, handle
) of
125 gen_tcp:close(Handle
),
126 {ok
, oop:set(This
, handle
, nil
)}