1 module common.network.client; 2 3 import hunt.logging; 4 import hunt.util.Serialize; 5 import hunt.raft; 6 import hunt.net; 7 import core.stdc.string; 8 import common.network; 9 import core.thread; 10 11 import std.bitmanip; 12 import std.stdint; 13 14 class Client : MessageTransfer 15 { 16 /// 17 this(ulong srcID , ulong dstID) 18 { 19 this.srcID = srcID; 20 this.dstID = dstID; 21 client = NetUtil.createNetClient(); 22 } 23 24 /// 25 void connect(string host , int port , ConnectHandler handler = null) 26 { 27 client.connect(port , host , 0 , ( Result!NetSocket result ){ 28 if(handler !is null) 29 handler(result); 30 if(!result.failed()) 31 sock = result.result(); 32 } ); 33 } 34 35 /// 36 void write(Message msg) 37 { 38 if(sock is null) 39 { 40 logWarning(srcID ," not connect now. " , dstID); 41 return; 42 } 43 44 //logDebug(srcID , " sendto " , dstID , " " , msg); 45 ubyte []data = cast(ubyte[])serialize(msg); 46 int len = cast(int)data.length; 47 ubyte[4] head = nativeToBigEndian(len); 48 49 sock.write(head ~ data); 50 } 51 52 void close() 53 { 54 sock.close(); 55 } 56 57 private: 58 ulong srcID; 59 ulong dstID; 60 NetClient client; 61 NetSocket sock = null; 62 } 63