-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathServer.cs
87 lines (69 loc) · 2.62 KB
/
Server.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace sshserver
{
public class Server
{
private IConfigurationRoot _Configuration;
private LoggerFactory _LoggerFactory;
private ILogger _Logger;
private const int DefaultPort = 22;
private const int ConectionBacklog = 64;
private TcpListener _Listener;
private List<Client> _Clients = new List<Client>();
public Server()
{
_Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("sshserver.json", optional:false)
.Build();
_LoggerFactory = new LoggerFactory();
_LoggerFactory.AddConsole(_Configuration.GetSection("Logging"));
_Logger = _LoggerFactory.CreateLogger("SSHServer");
}
public void Start()
{
Stop();
_Logger.LogInformation("Starting up...");
int port = _Configuration.GetValue<int>("port", DefaultPort);
_Listener = new TcpListener(IPAddress.Any, port);
_Listener.Start(ConectionBacklog);
_Logger.LogInformation($"Listening on port: {port}");
}
public void Stop()
{
if (_Listener != null)
{
_Logger.LogInformation("Shutting down...");
_Listener.Stop();
_Listener = null;
// Disconnect each client and clear list
_Clients.ForEach(c => c.Disconnect());
_Clients.Clear();
_Logger.LogInformation("Shutting down...");
}
}
public void Poll()
{
// Check for new connections
while (_Listener.Pending())
{
Task<Socket> acceptTask = _Listener.AcceptSocketAsync();
acceptTask.Wait();
Socket socket = acceptTask.Result;
_Logger.LogDebug($"New Client: {socket.RemoteEndPoint}");
_Clients.Add(new Client(socket, _LoggerFactory.CreateLogger(socket.RemoteEndPoint.ToString())));
}
// Poll each client
_Clients.ForEach(c => c.Poll());
// Remove all disconnected clients
_Clients.RemoveAll(c => c.IsConnected() == false);
}
}
}