anchor.diff:  	connected,
   	heart_beat,
   	miss,
  -	socket
  +	socket,
  +	buff
   	}).
   
   %%%===================================================================
   %%% API
   %%%===================================================================
  -
  +to_princess(ID,Bin)->
  +	gen_server:cast(?SERVER,{to_princess,ID,Bin}).
  +fetch(Pid,ID,Address,Port)->
  +	gen_server:call(?SERVER,{fetch,Pid,ID,Address,Port}).
   %%--------------------------------------------------------------------
   %% @doc
   %% Starts the server
  
positive.code: %%                                  {stop, Reason, State}
  %% @end
  %%--------------------------------------------------------------------
  handle_cast(_Msg, State) ->
  	{noreply, State}.
  
  
negative.code: %%%===================================================================
  %%% Internal functions
  %%%===================================================================
  loop_close()->
  	case ets:match_object(multiplex_mapper,{'_','_'}) of
  		[] ->
  			ok;
  		Any ->
  			loop_close(Any)
    end.
  loop_close([])->
  	ok;
  loop_close([H|T])->
  	{ID,_Pid} = H,
  	remote_close(ID),
  	loop_close(T).
  
  remote_close(ID)->
  	case ets:match_object(multiplex_mapper,{ID,'_'}) of
  		[] ->
  			ok;
  		[{ID,Pid}] ->
  			ets:delete(multiplex_mapper,ID),
  			hm_misc:demonitor(Pid,multiplex_monitor),
    		socks_protocol:close(Pid),
    		ok
    end.
  to_client(ID,Bin)->
  	case ets:match_object(multiplex_mapper,{ID,'_'}) of
  		[] ->
  			ok;
  		[{ID,Pid}] ->
    		socks_protocol:to_client(Pid,Bin),
    		ok
    end.
  
  packet([],State)->
  	State;
  packet([<<0:64/integer,0:32/integer>>|T],State)->
  	Miss = State#state.miss,
  	NewState = State#state{miss = Miss - 1},
  	lager:log(info,?MODULE,"pong~n"),
  	packet(T,NewState);
  
  packet([<<ID:64/integer,2:32/integer,Rest/bits>>|T],State)->
  	lager:log(info,?MODULE,"free->->client~n"),
  	to_client(ID,Rest),
  	packet(T,State);
  packet([<<ID:64/integer,3:32/integer,_Rest/bits>>|T],State)->
  	lager:log(info,?MODULE,"free close~n"),
  	remote_close(ID),
  	packet(T,State).
  
  pack(ID,OP,Data)->
  	R1 = <<ID:64/integer,OP:32/integer,Data/bits>>,
  	Len = erlang:byte_size(R1),
  	<<Len:32/big,R1/bits>>.
  
  unpack(Data,Acc) when byte_size(Data) < 4 ->
  	{lists:reverse(Acc),Data};
  unpack(<<Len:32/big,PayLoad/bits>> = Data,Acc) when Len > byte_size(PayLoad) ->
  	{lists:reverse(Acc),Data};
  unpack(<<Len:32/big, _/bits >> = Data, Acc) ->                                                                                                                                                                                                                                                 
    << _:32/big,Packet:Len/binary, Rest/bits >> = Data,
    unpack(Rest,[Packet|Acc]).