1 module hunt.imf.clients.GatewayTcpClient;
2 
3 import hunt.imf.clients.GatewayClient;
4 import hunt.imf.protocol.Protocol;
5 import hunt.imf.ConnectBase;
6 import hunt.imf.protocol.protobuf.ProtobufTcpConnection;
7 import hunt.imf.ConnectionEventBaseHandler;
8 import hunt.imf.protocol.protobuf.TcpConnectionEventHandler;
9 import hunt.imf.MessageBuffer;
10 import google.protobuf;
11 import std.array;
12 import hunt.net;
13 import core.thread;
14 import core.sync.condition;
15 import core.sync.mutex;
16 
17 class GatewayTcpClient : 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         _protocol = protocol;
32     }
33 
34     void onConnection (ConnectBase connection)
35     {
36         _condition.mutex().lock();
37         _conn = connection;
38         _condition.notify();
39         _condition.mutex().unlock();
40     }
41 
42     void connect()
43     {
44         NetClient client = NetUtil.createNetClient();
45         client.setCodec(_protocol.getCodec());
46         client.setHandler(_protocol.getHandler());
47         client.connect(_protocol.getHost(),_protocol.getPort());
48         _condition.mutex().lock();
49         _condition.wait();
50         _condition.mutex().unlock();
51         _netClient = client;
52     }
53 
54     void sendMsg(T)(int tid,T t)
55     {
56         if (_conn !is null)
57         {
58             MessageBuffer ask =  new MessageBuffer(tid,t.toProtobuf.array);
59             _conn.sendMsg(ask);
60         }
61     }
62 
63     void onClosed (ConnectBase connection)
64     {
65 
66     }
67 }
68