1 module server.server; 2 3 import std.socket : Socket, Address, SocketType, ProtocolType; 4 import client.client : ButterflyClient; 5 import std.file : mkdir, exists, isDir; 6 7 public final class ButterflyServer 8 { 9 /** 10 * TODO: Later implement listeners so that we can 11 * bind to multiple sockets. 12 */ 13 14 /** 15 * Socket to listen for incoming connections on 16 */ 17 private Socket serverSocket; 18 19 /** 20 * Whether or not the server is active 21 */ 22 private bool active = true; 23 24 /* TODO: Server domain */ 25 public string domain; 26 27 this(Address bindAddress, string domain) 28 { 29 /** 30 * Create the needed directories (if not already present) 31 */ 32 directoryCheck(); 33 34 /** 35 * Instantiate a new Socket for the given Address 36 * `bindAddress` of which it will bind to. 37 */ 38 serverSocket = new Socket(bindAddress.addressFamily, SocketType.STREAM, ProtocolType.TCP); 39 serverSocket.bind(bindAddress); 40 41 /* Set the domain of the server */ 42 this.domain = domain; 43 44 /* Start accepting connections */ 45 run(); 46 47 /* Close the socket */ 48 serverSocket.close(); 49 } 50 51 private void directoryCheck() 52 { 53 /* TODO: Create the `mailboxes/` directory, if it does not exist */ 54 55 /* Check to make sure there is a fs node at `mailboxes` */ 56 if(exists("mailboxes")) 57 { 58 /* Make sure it is a directory */ 59 if(isDir("mailboxes")) 60 { 61 62 } 63 else 64 { 65 /* TODO: Error handling */ 66 } 67 } 68 else 69 { 70 /* Create the `mailboxes` directory */ 71 mkdir("mailboxes"); 72 } 73 } 74 75 private void run() 76 { 77 /* TODO: backlog */ 78 /* Start accepting incoming connections */ 79 serverSocket.listen(1); 80 81 /* TODO: Loop here */ 82 while(active) 83 { 84 /* Block for an incoming queued connection */ 85 Socket clientSocket = serverSocket.accept(); 86 87 /** 88 * Create a new ButterflyClient to represent the 89 * client connection. 90 */ 91 ButterflyClient client = new ButterflyClient(this, clientSocket); 92 93 /* Start the client thread */ 94 client.start(); 95 96 /* TODO: Add to array */ 97 } 98 } 99 }