1 module hunt.imf.core.application; 2 3 import hunt.imf.core.dispatcher; 4 import hunt.imf.io.server; 5 import hunt.imf.io.client; 6 import hunt.imf.io.clientext; 7 import hunt.imf.io.context; 8 9 import hunt.net.NetUtil; 10 11 class Application 12 { 13 14 this() 15 { 16 _dispatcher = new Dispatcher(); 17 18 } 19 20 Server createServer(string host , int port , string namespace_="") 21 { 22 auto server = new Server(_dispatcher, namespace_); 23 _servers ~= server; 24 Addr addr = {host , port}; 25 _server_addrs ~= addr; 26 return server; 27 } 28 29 Client createClient(string host , int port , string namespace_="") 30 { 31 auto client = new Client(_dispatcher ,namespace_ ); 32 _clients ~= client; 33 Addr addr = {host , port}; 34 _client_addrs ~= addr; 35 return client; 36 } 37 38 /// supported reconnect. 39 Client createClientExt(string host , int port , string namespace_ = "") 40 { 41 auto client = new ClientExt(_dispatcher ,namespace_ ); 42 _clients ~= client; 43 Addr addr = {host , port}; 44 _client_addrs ~= addr; 45 return client; 46 } 47 48 void run(long timeout = -1) 49 { 50 NetUtil.startEventLoop(timeout); 51 _dispatcher.start(); 52 for(size_t i = 0 ; i < _servers.length ; i++) 53 _servers[i].listen(_server_addrs[i].port , _server_addrs[i].host); 54 for(size_t i = 0 ; i < _clients.length ; i++) 55 _clients[i].connect(_client_addrs[i].port , _client_addrs[i].host); 56 } 57 58 void stop() { 59 NetUtil.stopEventLoop(); 60 _dispatcher.stop(); 61 62 for(size_t i = 0 ; i < _servers.length ; i++) 63 _servers[i].stop(); 64 for(size_t i = 0 ; i < _clients.length ; i++) 65 _clients[i].stop(); 66 } 67 68 69 private: 70 71 Addr[] _server_addrs; 72 Addr[] _client_addrs; 73 Server[] _servers; 74 Client[] _clients; 75 Dispatcher _dispatcher; 76 77 78 struct Addr 79 { 80 string host; 81 int port; 82 } 83 }