1 /* 2 * Collie - An asynchronous event-driven network framework using Dlang development 3 * 4 * Copyright (C) 2015-2016 Shanghai Putao Technology Co., Ltd 5 * 6 * Developer: putao's Dlang team 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 module app; 12 13 import core.thread; 14 15 import std.datetime; 16 import std.stdio; 17 import std.functional; 18 import std.exception; 19 20 import collie.net; 21 import kiss.net.TcpStream; 22 import collie.net.client.client; 23 24 import core.thread; 25 import core.sync.semaphore; 26 27 @trusted class MyClient : BaseClient 28 { 29 this() 30 { 31 super(new EventLoop()); 32 } 33 34 void runInThread() 35 { 36 if (th !is null || isAlive) 37 return; 38 th = new Thread(() { eventLoop.run(); }); 39 th.start(); 40 } 41 42 void syncConnet(Address addr) 43 { 44 if (sem is null) 45 { 46 sem = new Semaphore(0); 47 } 48 _sync = true; 49 scope (failure) 50 _sync = false; 51 connect(addr, &onCreate); 52 sem.wait(); 53 } 54 55 protected: 56 override void onActive() nothrow 57 { 58 collectException({ 59 if (_sync) 60 sem.notify(); 61 writeln("Connection succeeded!"); 62 }()); 63 } 64 65 override void onFailure() nothrow 66 { 67 collectException({ 68 if (_sync) 69 sem.notify(); 70 writeln("Connection failed!"); 71 }()); 72 } 73 74 override void onClose() nothrow 75 { 76 collectException(writeln("Connection closed!")); 77 } 78 79 override void onRead(in ubyte[] data) nothrow 80 { 81 collectException(writeln("received data: ", cast(string) data)); 82 } 83 84 override void onTimeout(Object sender) 85 { 86 collectException({ 87 if (isAlive) 88 { 89 writeln("Timer ticked!"); 90 string data = Clock.currTime().toSimpleString(); 91 write(cast(ubyte[]) data, null); 92 } 93 }()); 94 } 95 96 void onCreate(TcpStream client) 97 { 98 // set client; 99 //client.setKeepAlive(1200,2); 100 writeln("A tcp client created!"); 101 } 102 103 private: 104 105 Thread th; 106 Semaphore sem; 107 bool _sync = false; 108 } 109 110 void main() 111 { 112 MyClient client = new MyClient(); 113 client.runInThread(); 114 client.setTimeout(60); 115 client.tryCount(3); 116 client.syncConnet(new InternetAddress("127.0.0.1", 8090)); 117 // client.syncConnet(new InternetAddress("10.1.222.120", 8090)); 118 //client.eventLoop.run(); 119 if (!client.isAlive) 120 { 121 writeln("Connection failed."); 122 return; 123 } 124 while (true) 125 { 126 writeln("input data to send to server: "); 127 string data = readln(); 128 if (data[$ - 1] == '\n') 129 data = data[0 .. $ - 1]; 130 if (data == "exit" || data == "quit") 131 { 132 client.close(); 133 break; 134 } 135 client.write(cast(ubyte[]) data, null); 136 } 137 }