1 module hunt.imf.io.client;
2 
3 import hunt.net;
4 
5 import hunt.imf.core.dispatcher;
6 import hunt.imf.protocol.parser;
7 import hunt.imf.protocol.packet;
8 import hunt.imf.io.context;
9 import hunt.logging;
10 
11 import std.socket;
12 import std.conv;
13 
14 class Client
15 {
16     this(Dispatcher dispatcher , string ns = "")
17     {
18         _dispatcher = dispatcher;
19         _client = NetUtil.createNetClient();
20         _namespace = ns;
21     }
22 
23     void connect(int port , string host = "127.0.0.1")
24     {
25         string strPort = to!string(port);
26 		AddressInfo[] arr = getAddressInfo(host , strPort , AddressInfoFlags.CANONNAME);
27 		if(arr.length == 0 && arr[0].family == AF_INET)
28 		{
29 			throw new Exception("can't parse " ~ host ~ " or ipv6");
30 		}
31     
32         host = arr[0].address.toAddrString;
33         
34         _client.connect(port , host ,0, (Result!NetSocket result){
35             if(result.failed())
36             {
37                 logError(result.cause.msg);
38                 return;
39             }
40             auto tcp = cast(AsynchronousTcpSession)result.result();
41             auto context = new Context(_namespace , tcp);
42             tcp.attachObject(context);
43             if(_open !is null)
44                 _open(context);
45 
46             tcp.closeHandler((){
47                 if(_close !is null)
48                     _close(context);
49             });
50             tcp.handler((in ubyte[] data){
51                 auto context = cast(Context)tcp.getAttachment();
52                 auto list = context.parser.consume(cast(byte[])data);
53                 foreach(p ; list)
54                     _dispatcher.dispatch(context , p);
55                 });   
56         });
57 
58     }
59 
60     void stop() {
61         _client.stop();
62     }
63 
64     void setOpenHandler(OpenHandler handler)
65     {
66         _open = handler;
67     }
68 
69     void setCloseHandler(CloseHandler handler){
70         _close = handler;
71     }
72 
73 protected:
74     string          _namespace;
75     Dispatcher      _dispatcher;
76     NetClient       _client;
77     OpenHandler     _open;
78     CloseHandler    _close;
79 }