besterd/source/listeners/listener.d

93 lines
2.0 KiB
D
Raw Normal View History

2020-04-24 17:48:22 +02:00
module listeners.listener;
2020-04-16 15:02:34 +02:00
import utils.debugging : debugPrint;
import std.conv : to;
import std.socket : Socket, AddressFamily, SocketType, ProtocolType, parseAddress, SocketFlags, Address;
2020-04-16 17:05:56 +02:00
import core.thread : Thread;
2020-04-17 18:47:05 +02:00
import std.stdio : writeln, File;
2020-04-18 15:25:22 +02:00
import std.json : JSONValue, parseJSON, JSONException, JSONType, toJSON;
import std.string : cmp;
import handlers.handler;
2020-04-24 17:48:22 +02:00
import server.server;
import connection.connection;
2020-05-07 21:22:10 +02:00
/**
* Represents a server listener which is a method
* by which conections to the server (client or server)
* can be made.
*/
public class BesterListener : Thread
{
/* The associated BesterServer */
private BesterServer server;
/* The server's socket */
private Socket serverSocket;
/* Whether or not the listener is active */
private bool active = true;
/* the address of this listener */
protected Address address;
this(BesterServer besterServer)
{
2020-04-20 18:50:00 +02:00
/* Set the function address to be called as the worker function */
2020-04-20 18:55:48 +02:00
super(&run);
2020-04-20 18:50:00 +02:00
/* Set this listener's BesterServer */
this.server = besterServer;
}
2020-05-07 22:34:29 +02:00
/**
* Set the server socket.
*/
public void setServerSocket(Socket serverSocket)
{
/* Set the server socket */
this.serverSocket = serverSocket;
/* Set the address */
address = serverSocket.localAddress();
}
/**
* Get the server socket.
*/
public Socket getServerSocket()
{
return serverSocket;
}
2020-05-07 22:34:29 +02:00
/**
* Start listen loop.
*/
public void run()
{
serverSocket.listen(1); /* TODO: This value */
debugPrint("Server listen loop started");
2020-05-07 22:34:29 +02:00
/* Loop receive and dispatch connections whilst active */
while(active)
{
/* Wait for an incoming connection */
Socket clientConnection = serverSocket.accept();
/* Create a new client connection handler and start its thread */
BesterConnection besterConnection = new BesterConnection(clientConnection, server);
besterConnection.start();
/* Add this client to the list of connected clients */
server.clients ~= besterConnection;
}
/* Close the socket */
serverSocket.close();
}
public void shutdown()
{
active = false;
}
}