Skip to content

Commit

Permalink
Merge pull request #6 from MattEstHaut/feature/server
Browse files Browse the repository at this point in the history
Ajoute les fonctionnalités essentielles du serveur
  • Loading branch information
MattEstHaut authored May 31, 2024
2 parents 7522586 + 3d414b0 commit b35b0ef
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 1 deletion.
44 changes: 44 additions & 0 deletions src/Server/Connection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System.Net.Sockets;
using Shared.Comm;
using Shared.Resp;

public class ConnectionHandler
{
private readonly CommandManager _manager;

public ConnectionHandler(CommandManager manager)
{
_manager = manager;
}

public void Handle(TcpClient socket)
{
using var client = new Client(socket);

try
{
while (socket.Connected)
{
var request = client.Read();

if (request is not ItemArray array)
throw new Exception("Expected array");

var args = array.Items.ConvertAll(i => i.ToString() ?? "").ToArray();

if (args.Length == 0)
throw new Exception("Expected at least 1 argument");

var command = args[0];
var response = _manager.Execute(command, args[1..]);
client.Send(response);
}
}
finally { }
}

public async Task HandleAsync(TcpClient socket)
{
await Task.Run(() => Handle(socket));
}
}
8 changes: 7 additions & 1 deletion src/Server/Program.cs
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
Console.WriteLine("Hello, World!");
int port = 6379;

if (args.Length > 0) port = int.Parse(args[0]);

var database = new Database(15000);
var server = new Server(port, database);
server.Run();
36 changes: 36 additions & 0 deletions src/Server/Server.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Net;
using System.Net.Sockets;

public class Server
{
private readonly TcpListener _listener;
private readonly ConnectionHandler _handler;
private readonly CommandManager _manager;

public Server(int port, Database db)
{
_listener = new TcpListener(IPAddress.Any, port);
_manager = new CommandManager(db);
_handler = new ConnectionHandler(_manager);
}

public void Run()
{
_listener.Start();
_ = _manager.StartAsync();

while (_listener.Server.IsBound)
{
var socket = _listener.AcceptTcpClient();
_ = _handler.HandleAsync(socket);
}
}

public void Stop()
{
_listener.Stop();
_manager.Stop();
}

public void RunAsync() => Task.Run(() => Run());
}

0 comments on commit b35b0ef

Please sign in to comment.