1 /* 2 * NetKit - This library contains tcp / http / http2 / websocket servers and clients. 3 * 4 * Copyright (C) 2015-2017 Shanghai Putao Technology Co., Ltd 5 * 6 * Developer: HuntLabs 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module netkit.net.NetClient; 13 14 import netkit.common.Common; 15 import netkit.net.NetClientOptions; 16 import netkit.net.NetClientSocket; 17 import netkit.net.ServerBootstrap; 18 import netkit.Netkit; 19 20 import std.socket; 21 22 23 class NetClient { 24 25 public this(Netkit netkit, NetClientOptions options) 26 { 27 _options = options; 28 } 29 30 public NetClient connect(string ip, ushort port, connet_handler handler = null) 31 { 32 if (_options._block) 33 { 34 _blockSocket = new TcpSocket(); 35 _blockSocket.connect(new InternetAddress(ip, port)); 36 } 37 else 38 { 39 _bootStrap = new ServerBootstrap(); 40 _connectHandler = handler; 41 _clientSocket = new NetClientSocket(_bootStrap); 42 _clientSocket.setConnectHandler(_connectHandler); 43 _clientSocket.connect(ip, port); 44 _bootStrap.start(); 45 } 46 return this; 47 } 48 49 public long read(byte[] buf) 50 { 51 if (_options._block) { 52 return _blockSocket.receive(buf); 53 } 54 else { 55 return -1; 56 } 57 } 58 59 public long write(byte[] buf) 60 { 61 if (_options._block) { 62 return _blockSocket.send(buf); 63 } 64 else { 65 return -1; 66 } 67 } 68 69 public void close() 70 { 71 if (_options._block) { 72 _blockSocket.close(); 73 } 74 else { 75 _clientSocket.close(); 76 } 77 } 78 79 80 81 private: 82 connet_handler _connectHandler; 83 NetClientSocket _clientSocket; 84 ServerBootstrap _bootStrap; 85 NetClientOptions _options; 86 Socket _blockSocket; 87 88 89 90 }