1 module hunt.imf.io.context;
2 
3 import hunt.net;
4 
5 
6 import hunt.imf.protocol.packet;
7 import hunt.imf.protocol.parser;
8 
9 import google.protobuf;
10 
11 import std.array;
12 import std.stdio;
13 import std.stdint;
14 
15 import hunt.Functions;
16 
17 alias VoidHandler = SimpleEventHandler;
18 
19 class Context
20 {
21     this(string ns , NetSocket sock)
22     {
23         _namespace = ns;
24         _sock = sock;
25         _parser = new Parser();
26     }
27 
28     string ns() @property
29     {
30         return _namespace;
31     }
32 
33     NetSocket sock() @property
34     {
35         return _sock;
36     }
37 
38     Parser parser() @property
39     {
40         return _parser;
41     }
42 
43     Object getAttachment() 
44     {
45         return object;
46     }
47 
48     void setAttachment(Object attachment) 
49     {
50         object = attachment;
51     }
52     string      _namespace;
53     NetSocket   _sock;
54     Parser      _parser;
55     
56     
57     Object      object;
58 }
59 
60 alias OpenHandler = void delegate(Context context);
61 alias CloseHandler = void delegate(Context context);
62 
63 
64 static Context g_context;
65 
66 Context context() @property
67 {
68     return g_context;
69 }
70 
71 void setContext(Context context)
72 {
73     g_context = context;
74 }
75 
76 void sendMessage(M)(Context context,int64_t message_id , M m , VoidHandler finish = null)
77 {
78     auto packet = new Packet(message_id ,  m.toProtobuf.array);
79     auto data = packet.data;
80     context.sock.write(packet.data , finish);
81 }
82 
83 void sendMessage(Context context,int64_t message_id ,VoidHandler finish = null )
84 {
85     auto packet = new Packet(message_id);
86     auto data = packet.data;
87     context.sock.write(packet.data,finish);
88 }
89 
90 void close(Context context)
91 {
92     context.sock.close();
93 }