blob: 76257c11a8c424b0a89ed09a80c64e3267b1b019 [file] [log] [blame]
Christopher Piro094823a2007-07-18 00:26:12 +00001%%% Copyright (c) 2007- Facebook
2%%% Distributed under the Thrift Software License
Christopher Piro53b6ef62007-11-15 06:26:28 +00003%%%
Christopher Piro094823a2007-07-18 00:26:12 +00004%%% See accompanying file LICENSE or visit the Thrift site at:
5%%% http://developers.facebook.com/thrift/
6
7-module(tServerSocket).
8
9-include("oop.hrl").
10-include("thrift.hrl").
11-include("transport/tServerSocket.hrl").
12
13-behavior(oop).
14
15-export([attr/4, super/0, inspect/1]).
16
17-export([new/1, effectful_listen/1, accept/1, effectful_close/1]).
18
19%%%
20%%% define attributes
21%%% 'super' is required unless ?MODULE is a base class
22%%%
23
24?DEFINE_ATTR(super);
25?DEFINE_ATTR(port);
26?DEFINE_ATTR(handle).
Christopher Piro53b6ef62007-11-15 06:26:28 +000027
Christopher Piro094823a2007-07-18 00:26:12 +000028%%%
29%%% behavior callbacks
30%%%
Christopher Piro53b6ef62007-11-15 06:26:28 +000031
Christopher Piro094823a2007-07-18 00:26:12 +000032%%% super() -> SuperModule = atom()
33%%% | none
34
35super() ->
36 tServerTransport.
37
38%%% inspect(This) -> string()
39
40inspect(This) ->
41 ?FORMAT_ATTR(port) ++ ", " ++
42 ?FORMAT_ATTR(handle).
43
44%%%
45%%% class methods
46%%%
47
48new(Port) ->
49 Super = (super()):new(),
50 #?MODULE{super = Super, port = Port, handle = nil}.
51
52%%%
53%%% instance methods
54%%%
55
56effectful_listen(This) ->
57 Port = oop:get(This, port),
58 Options = [binary, {packet, 0}, {active, false}], % was []
59
Christopher Piro53b6ef62007-11-15 06:26:28 +000060 case gen_tcp:listen(Port, Options) of
61 {ok, ListenSocket} ->
62 This1 = oop:set(This, handle, ListenSocket),
63 {ok, This1}
64
65 %% {error, _} ->
66 %% TODO: no error handling in Ruby version?
Christopher Piro094823a2007-07-18 00:26:12 +000067 end.
68
69accept(This) ->
Christopher Piro53b6ef62007-11-15 06:26:28 +000070 case oop:get(This, handle) of
71 nil ->
72 nil; % cpiro: sic the Ruby code
Christopher Piro094823a2007-07-18 00:26:12 +000073
Christopher Piro53b6ef62007-11-15 06:26:28 +000074 Handle ->
75 case gen_tcp:accept(Handle) of
76 {ok, Sock} ->
77 Trans = oop:start_new(tSocket, []),
78 ?R1(Trans, effectful_setHandle, Sock),
79 Trans
80 %% {error, _} ->
81 %% TODO: no error handling in Ruby version?
82 end
Christopher Piro094823a2007-07-18 00:26:12 +000083 end.
84
85effectful_close(This) ->
Christopher Piro53b6ef62007-11-15 06:26:28 +000086 case oop:get(This, handle) of
87 nil ->
88 {nil, This};
89 Handle ->
90 case gen_tcp:close(Handle) of
91 ok ->
92 {ok, This} % cpiro: sic the Ruby version: don't set handle to nil
93 %% {error, _} ->
94 %% TODO: no error handling in Ruby version?
95 end
Christopher Piro094823a2007-07-18 00:26:12 +000096 end.