1 module client; 2 3 import hunt.net; 4 import hunt.net.codec.textline; 5 import hunt.logging.ConsoleLogger; 6 import hunt.String; 7 8 import std.format; 9 import std.stdio; 10 11 12 enum Host = "127.0.0.1"; 13 enum Port = 8080; 14 15 16 void main() { 17 int count = 0; 18 NetClient client = NetUtil.createNetClient(); 19 20 client.setCodec(new TextLineCodec); 21 22 // dfmt off 23 client.setHandler(new class NetConnectionHandler { 24 25 override void connectionOpened(Connection connection) { 26 infof("Connection created: %s", connection.getRemoteAddress()); 27 28 // connection.write("Hi, I'm client"); 29 connection.encode(new String("Hi, I'm client\r")); 30 } 31 32 override void connectionClosed(Connection connection) { 33 infof("Connection closed: %s", connection.getRemoteAddress()); 34 35 // client.close(); 36 } 37 38 override void messageReceived(Connection connection, Object message) { 39 tracef("message type: %s", typeid(message).name); 40 string str = format("data received: %s", message.toString()); 41 tracef(str); 42 if(count< 10) { 43 connection.encode(new String(str)); 44 } else if(count == 10) { 45 connection.encode(new String("No data will be sent from now.")); 46 } 47 count++; 48 } 49 50 override void exceptionCaught(Connection connection, Throwable t) { 51 warning(t); 52 } 53 54 override void failedOpeningConnection(int connectionId, Throwable t) { 55 warning(t); 56 client.close(); 57 } 58 59 override void failedAcceptingConnection(int connectionId, Throwable t) { 60 warning(t); 61 } 62 }).connect(Host, Port); 63 64 // dfmt on 65 }