1 module listeners.listener; 2 3 import utils.debugging : debugPrint; 4 import std.conv : to; 5 import std.socket : Socket, AddressFamily, SocketType, ProtocolType, parseAddress, SocketFlags, Address; 6 import core.thread : Thread; 7 import std.stdio : writeln, File; 8 import std.json : JSONValue, parseJSON, JSONException, JSONType, toJSON; 9 import std.string : cmp; 10 import handlers.handler; 11 import server.server; 12 import connection.connection; 13 import base.types : BesterException; 14 15 /** 16 * Represents a server listener which is a method 17 * by which conections to the server (client or server) 18 * can be made. 19 */ 20 public class BesterListener : Thread 21 { 22 /* The associated BesterServer */ 23 private BesterServer server; 24 25 /* The server's socket */ 26 private Socket serverSocket; 27 28 /* Whether or not the listener is active */ 29 private bool active = true; 30 31 /* the address of this listener */ 32 protected Address address; 33 34 this(BesterServer besterServer) 35 { 36 /* Set the function address to be called as the worker function */ 37 super(&run); 38 39 /* Set this listener's BesterServer */ 40 this.server = besterServer; 41 } 42 43 /** 44 * Set the server socket. 45 */ 46 public void setServerSocket(Socket serverSocket) 47 { 48 /* Set the server socket */ 49 this.serverSocket = serverSocket; 50 51 /* Set the address */ 52 address = serverSocket.localAddress(); 53 } 54 55 /** 56 * Get the server socket. 57 */ 58 public Socket getServerSocket() 59 { 60 return serverSocket; 61 } 62 63 /** 64 * Start listen loop. 65 */ 66 public void run() 67 { 68 serverSocket.listen(1); /* TODO: This value */ 69 debugPrint("Server listen loop started"); 70 71 /* Loop receive and dispatch connections whilst active */ 72 while(active) 73 { 74 /* Wait for an incoming connection */ 75 Socket clientConnection = serverSocket.accept(); 76 77 /* Create a new client connection handler and start its thread */ 78 BesterConnection besterConnection = new BesterConnection(clientConnection, server); 79 besterConnection.start(); 80 81 /* Add this client to the list of connected clients */ 82 server.addConnection(besterConnection); 83 } 84 85 /* Close the socket */ 86 serverSocket.close(); 87 } 88 89 public void shutdown() 90 { 91 active = false; 92 } 93 } 94 95 public final class BesterListenerException : BesterException 96 { 97 this(BesterListener e) 98 { 99 super("Could not bind to: " ~ e.toString()); 100 } 101 }