1 module hunt.imf.clients.GatewayHttpClient;
2 
3 import hunt.imf.clients.GatewayClient;
4 import hunt.imf.protocol.Protocol;
5 import hunt.imf.ConnectBase;
6 import hunt.imf.ConnectionEventBaseHandler;
7 import hunt.imf.protocol.http.HttpConnection;
8 import hunt.imf.MessageBuffer;
9 import hunt.imf.ParserBase;
10 import hunt.util.Serialize;
11 import hunt.net;
12 import core.thread;
13 import core.sync.condition;
14 import core.sync.mutex;
15 import hunt.logging;
16 
17 class GatewayHttpClient : GatewayClient {
18 
19     private {
20         Condition _condition;
21         ConnectBase _conn = null;
22         Protocol _protocol;
23         NetClient _netClient;
24     }
25 
26     this(Protocol protocol) {
27         _condition = new Condition(new Mutex());
28         ConnectionEventBaseHandler handler = cast(ConnectionEventBaseHandler)protocol.getHandler();
29         handler.setOnConnection(&this.onConnection);
30         handler.setOnClosed(&this.onClosed);
31         handler.setOnMessage(&this.onMessage);
32         _protocol = protocol;
33     }
34 
35     void onConnection (ConnectBase connection)
36     {
37         _condition.mutex().lock();
38         _condition.notify();
39         _condition.mutex().unlock();
40          connection.getConnection().setAttribute("CLIENT");
41         _conn = connection;
42     }
43 
44     void connect()
45     {
46         NetClient client = NetUtil.createNetClient();
47         client.setCodec(_protocol.getCodec());
48         client.setHandler(_protocol.getHandler());
49         client.connect(_protocol.getHost(),_protocol.getPort());
50         _condition.mutex().lock();
51         _condition.wait();
52         _condition.mutex().unlock();
53         _netClient = client;
54     }
55 
56     void sendMsg(ref HttpContent content)
57     {
58         if (_conn !is null)
59         {
60             MessageBuffer ask = new MessageBuffer(0,cast(ubyte[])serialize!HttpContent(content));
61             _conn.sendMsg(ask);
62         }
63     }
64 
65 
66     void onMessage(Connection conneciton, Object message)
67     {
68         MessageBuffer msg = cast(MessageBuffer)message;
69         HttpContent  content = unserialize!HttpContent(cast(byte[])msg.message);
70         tracef("%s",content.body);
71         conneciton.close();
72     }
73 
74     void onClosed (ConnectBase connection)
75     {
76 
77     }
78 
79 }
80