Skip to content

Commit 00cbd31

Browse files
committed
refactor
1 parent aa3f53e commit 00cbd31

3 files changed

Lines changed: 125 additions & 117 deletions

File tree

Interface.CMD/ConsoleCommand.cs

Lines changed: 52 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -11,31 +11,21 @@ namespace phat.Interface.CMD
1111
{
1212
internal class ConsoleCommand
1313
{
14-
[DefaultCommand()]
14+
[DefaultCommand]
1515
public void Info()
1616
{
1717
AnsiConsole.Write(new FigletText(Settings.AppTitle)
1818
.LeftAligned()
1919
.Color(Color.Red));
20-
AnsiConsole.Write(new Panel($"{Settings.AppDescription} [black on yellow rapidblink] {Settings.AppRepoURL} [/] [white on royalblue1] {Settings.AppVersion} [/]"));
20+
AnsiConsole.Write(new Panel(
21+
$"{Settings.AppDescription} [black on yellow rapidblink] {Settings.AppRepoURL} [/] [white on royalblue1] {Settings.AppVersion} [/]"));
2122
}
2223

2324

24-
[Command("host", Description = "Host a local chat session", ArgumentSeparatorStrategy = ArgumentSeparatorStrategy.PassThru)]
25+
[Command("host", Description = "Host a local chat session",
26+
ArgumentSeparatorStrategy = ArgumentSeparatorStrategy.PassThru)]
2527
public void Host(CommandContext ctx, [Option('b')] bool beep)
2628
{
27-
TcpClient onStart(TcpListener listener)
28-
{
29-
var f = ConnectionService.FlattenIPEndpoint((IPEndPoint)listener.LocalEndpoint);
30-
31-
return AnsiConsole.Status()
32-
.Start($"Chat session started at {f.Item1}:{f.Item2}", ctx =>
33-
{
34-
TcpClient client = listener.AcceptTcpClient();
35-
onConnectPrint(client, true);
36-
return client;
37-
});
38-
}
3929
var args = ctx.ParseResult!.SeparatedArguments;
4030
var ipChecker = new RegularExpressionAttribute(Settings.IPAddressRegex);
4131
var portChecker = new RangeAttribute(1024, 65535);
@@ -45,26 +35,27 @@ TcpClient onStart(TcpListener listener)
4535
switch (args.Count)
4636
{
4737
case 0:
48-
remoteClient = ConnectionService.Create(onStart);
38+
remoteClient = ConnectionService.Create(OnStart);
4939
break;
5040
case 1:
51-
string value = args.First();
41+
var value = args.First();
5242
if (value.Length <= 5)
5343
{
5444
Validate(true, portChecker.IsValid(value));
55-
remoteClient = ConnectionService.Create(int.Parse(value), onStart);
45+
remoteClient = ConnectionService.Create(int.Parse(value), OnStart);
5646
}
5747
else
5848
{
5949
Validate(ipChecker.IsValid(value), true);
60-
remoteClient = ConnectionService.Create(IPAddress.Parse(value), onStart);
50+
remoteClient = ConnectionService.Create(IPAddress.Parse(value), OnStart);
6151
}
52+
6253
break;
6354
case 2:
64-
string? ipArg = args.ElementAt(0);
65-
string? portArg = args.ElementAt(1);
55+
var ipArg = args.ElementAt(0);
56+
var portArg = args.ElementAt(1);
6657
Validate(ipChecker.IsValid(ipArg), portChecker.IsValid(portArg));
67-
remoteClient = ConnectionService.Create(IPAddress.Parse(ipArg), int.Parse(portArg), onStart);
58+
remoteClient = ConnectionService.Create(IPAddress.Parse(ipArg), int.Parse(portArg), OnStart);
6859
break;
6960
default:
7061
throw new ConsoleException("Invalid arguments!, Expected: [<ip> <port>]");
@@ -77,38 +68,55 @@ TcpClient onStart(TcpListener listener)
7768

7869
StartMessaging(remoteClient);
7970
Settings.beepOnIncomingMessage = beep;
71+
return;
72+
73+
TcpClient OnStart(TcpListener listener)
74+
{
75+
var f = ConnectionService.FlattenIPEndpoint((IPEndPoint)listener.LocalEndpoint);
76+
77+
return AnsiConsole.Status()
78+
.Start($"Chat session started at {f.Item1}:{f.Item2}", _ =>
79+
{
80+
var client = listener.AcceptTcpClient();
81+
OnConnectPrint(client, true);
82+
return client;
83+
});
84+
}
8085
}
8186

82-
private static void Validate(bool validIP = true, bool validPort = true) {
83-
StringBuilder stringBuilder = new StringBuilder();
84-
if (!validIP) stringBuilder.AppendLine("Invalid IP address!");
85-
if (!validPort) stringBuilder.AppendLine("Invalid ephemeral port! must be exclusively between 1024 and 65535.");
86-
if (stringBuilder.Length != 0) throw new ConsoleException(stringBuilder.ToString());
87+
private static void Validate(bool validIp = true, bool validPort = true)
88+
{
89+
var stringBuilder = new StringBuilder();
90+
if (!validIp) stringBuilder.AppendLine("Invalid IP address!");
91+
if (!validPort)
92+
stringBuilder.AppendLine("Invalid ephemeral port! must be exclusively between 1024 and 65535.");
93+
if (stringBuilder.Length != 0) throw new ConsoleException(stringBuilder.ToString());
8794
}
8895

8996
[Command("join", Description = "Join a chat session")]
90-
public void Join([Option('b')] bool beep, [RegularExpression(Settings.IPAddressRegex)] string ipAddress, [Range(1024, 65535)] int port)
97+
public void Join([Option('b')] bool beep, string ipAddress,
98+
[Range(1024, 65535)] int port)
9199
{
92-
TcpClient remoteClient = ConnectionService.Connect(IPAddress.Parse(ipAddress), port, client =>
100+
var remoteClient = ConnectionService.Connect(IPAddress.Parse(ipAddress), port, client =>
93101
{
94-
var f = ConnectionService.FlattenIPEndpoint(ConnectionService.GetRemoteClientEndpoint(client)!);
102+
ConnectionService.FlattenIPEndpoint(ConnectionService.GetRemoteClientEndpoint(client)!);
95103
AnsiConsole.Status()
96-
.Start("Attempting to Join", ctx =>
97-
{
98-
if (client.Connected)
99-
{
100-
onConnectPrint(client);
101-
}
102-
});
104+
.Start("Attempting to Join", _ =>
105+
{
106+
if (client.Connected)
107+
{
108+
OnConnectPrint(client);
109+
}
110+
});
103111
}, 5, 1000);
104112
StartMessaging(remoteClient);
105113
Settings.beepOnIncomingMessage = beep;
106114
}
107115

108-
private void StartMessaging(TcpClient client)
116+
private static void StartMessaging(TcpClient client)
109117
{
110118
MessageService ms = new(client);
111-
Console.CancelKeyPress += (args, sender) =>
119+
Console.CancelKeyPress += (_, _) =>
112120
{
113121
ms.Dispose();
114122
Rule rule = new("[red]Exited[/]")
@@ -123,18 +131,19 @@ private void StartMessaging(TcpClient client)
123131
co.Start();
124132
}
125133

126-
void onConnectPrint(TcpClient client, bool reverse = false)
134+
private static void OnConnectPrint(TcpClient client, bool reverse = false)
127135
{
128136
var r = ConnectionService.FlattenIPEndpoint(ConnectionService.GetRemoteClientEndpoint(client)!);
129137
var l = ConnectionService.FlattenIPEndpoint(ConnectionService.GetLocalClientEndpoint(client)!);
130138

131-
Rule rule = new($"[green]Connected at {DateTime.Now} :[/] [black on yellow] {l.Item1}:{l.Item2} (You) [/] {(reverse ? "<-" : "->")} [black on aqua] {r.Item1}:{r.Item2} [/]")
139+
Rule rule = new(
140+
$"[green]Connected at {DateTime.Now} :[/] [black on yellow] {l.Item1}:{l.Item2} (You) [/] {(reverse ? "<-" : "->")} [black on aqua] {r.Item1}:{r.Item2} [/]")
132141
{
133-
Alignment = Justify.Left
142+
Alignment = Justify.Left,
134143
};
135144
AnsiConsole.WriteLine("");
136145
AnsiConsole.Write(rule);
137146
AnsiConsole.WriteLine("");
138147
}
139148
}
140-
}
149+
}

Interface.CMD/ConsoleOperation.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace phat.Interface.CMD
88
internal class ConsoleOperation
99
{
1010
private readonly MessageService _messageService;
11-
private const int POLL_RATE_MIL = 1000 * 2;
11+
private const int PollRateMil = 1000 * 2;
1212

1313
public ConsoleOperation(MessageService messageService)
1414
{
@@ -65,13 +65,13 @@ internal void Start()
6565
StartMessageWriteOperation();
6666
Socket socketClient = _messageService.Client.Client;
6767
var f = ConnectionService.GetRemoteClientEndpoint;
68-
Thread ConnectionStateThread = new(() =>
68+
Thread connectionStateThread = new(() =>
6969
{
7070
var tp = IPGlobalProperties.GetIPGlobalProperties();
7171

7272
while (true)
7373
{
74-
Thread.Sleep(POLL_RATE_MIL);
74+
Thread.Sleep(PollRateMil);
7575
TcpState? tcpState = tp.GetActiveTcpConnections().FirstOrDefault(x => x.LocalEndPoint.Equals(socketClient.LocalEndPoint))?.State;
7676

7777
if (tcpState == null || tcpState == TcpState.Unknown || tcpState == TcpState.CloseWait || tcpState == TcpState.Closed)
@@ -87,7 +87,7 @@ internal void Start()
8787
AnsiConsole.WriteLine("");
8888
AnsiConsole.Write(rule);
8989
});
90-
ConnectionStateThread.Start();
90+
connectionStateThread.Start();
9191
}
9292

9393
public static string getCurrentTime() => DateTime.Now.ToLongTimeString();

Services/ConnectionService.cs

Lines changed: 69 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -3,101 +3,100 @@
33
using System.Net;
44
using System.Net.Sockets;
55

6-
namespace phat.Services
7-
{
8-
internal delegate TcpClient onStartHandler(TcpListener listener);
9-
10-
internal delegate void onConnectHandler(TcpClient client);
6+
namespace phat.Services;
117

8+
internal delegate TcpClient onStartHandler(TcpListener listener);
129

13-
internal static class ConnectionService
14-
{
15-
internal static TcpClient Create(onStartHandler onStart) => Create(GetLocalIPAddress(), 0, onStart);
10+
internal delegate void onConnectHandler(TcpClient client);
1611

17-
internal static TcpClient Create(IPAddress localIP, onStartHandler onStart) => Create(localIP, 0, onStart);
1812

19-
internal static TcpClient Create(int localPort, onStartHandler onStart) =>
20-
Create(GetLocalIPAddress(), localPort, onStart);
21-
22-
internal static TcpClient Create(IPAddress localIP, int localPort, onStartHandler onStart)
23-
{
24-
IPEndPoint localEP = new(localIP, localPort);
25-
TcpListener listener = new(localEP);
26-
listener.Start();
27-
return onStart.Invoke(listener);
28-
}
13+
internal static class ConnectionService
14+
{
15+
internal static TcpClient Create(onStartHandler onStart) => Create(GetLocalIPAddress(), 0, onStart);
2916

30-
private static (TcpClient, IPEndPoint) GetClientWithEndpoint(IPAddress remoteIP, int remotePort) => (
31-
new TcpClient(AddressFamily.InterNetwork), new IPEndPoint(remoteIP, remotePort));
17+
internal static TcpClient Create(IPAddress localIP, onStartHandler onStart) => Create(localIP, 0, onStart);
3218

33-
private static void Connect(TcpClient client, IPEndPoint remoteEP, onConnectHandler onConnect)
34-
{
35-
client.Connect(remoteEP);
36-
onConnect.Invoke(client);
37-
}
19+
internal static TcpClient Create(int localPort, onStartHandler onStart) =>
20+
Create(GetLocalIPAddress(), localPort, onStart);
3821

39-
internal static TcpClient Connect(IPAddress remoteIP,
40-
int remotePort,
41-
onConnectHandler onConnect,
42-
[Range(1, 8)] int retry,
43-
[Range(1_000, 10_000)] int retryDuration)
44-
{
45-
int attempt = 0;
46-
int socketErrorCode = 0;
47-
(TcpClient client, IPEndPoint remoteEP) = GetClientWithEndpoint(remoteIP, remotePort);
48-
while (attempt <= retry)
49-
{
50-
try
51-
{
52-
Console.WriteLine("Attempting to connect: {0}", attempt);
53-
if (attempt != 0) Thread.Sleep(retryDuration);
54-
Connect(client, remoteEP, onConnect);
55-
return client;
56-
}
57-
catch (SocketException se)
58-
{
59-
attempt++;
60-
socketErrorCode = se.ErrorCode;
61-
}
62-
}
22+
internal static TcpClient Create(IPAddress localIP, int localPort, onStartHandler onStart)
23+
{
24+
IPEndPoint localEP = new(localIP, localPort);
25+
TcpListener listener = new(localEP);
26+
listener.Start();
27+
return onStart.Invoke(listener);
28+
}
6329

64-
client.Dispose();
65-
throw new ConnectException(socketErrorCode);
66-
}
30+
private static (TcpClient, IPEndPoint) GetClientWithEndpoint(IPAddress remoteIP, int remotePort) => (
31+
new TcpClient(AddressFamily.InterNetwork), new IPEndPoint(remoteIP, remotePort));
6732

33+
private static void Connect(TcpClient client, IPEndPoint remoteEP, onConnectHandler onConnect)
34+
{
35+
client.Connect(remoteEP);
36+
onConnect.Invoke(client);
37+
}
6838

69-
internal static TcpClient Join(IPAddress remoteIP, int remotePort, onConnectHandler onConnect)
39+
internal static TcpClient Connect(IPAddress remoteIP,
40+
int remotePort,
41+
onConnectHandler onConnect,
42+
[Range(1, 8)] int retry,
43+
[Range(1_000, 10_000)] int retryDuration)
44+
{
45+
int attempt = 0;
46+
int socketErrorCode = 0;
47+
(TcpClient client, IPEndPoint remoteEP) = GetClientWithEndpoint(remoteIP, remotePort);
48+
while (attempt <= retry)
7049
{
71-
(TcpClient client, IPEndPoint remoteEP) = GetClientWithEndpoint(remoteIP, remotePort);
7250
try
7351
{
52+
Console.WriteLine("Attempting to connect: {0}", attempt);
53+
if (attempt != 0) Thread.Sleep(retryDuration);
7454
Connect(client, remoteEP, onConnect);
7555
return client;
7656
}
7757
catch (SocketException se)
7858
{
79-
client.Dispose();
80-
throw new ConnectException(se.ErrorCode);
59+
attempt++;
60+
socketErrorCode = se.ErrorCode;
8161
}
8262
}
8363

84-
public static IPAddress GetLocalIPAddress()
85-
{
86-
var host = Dns.GetHostEntry(Dns.GetHostName());
87-
var ip = host.AddressList.FirstOrDefault(a =>
88-
a.AddressFamily == AddressFamily.InterNetwork &&
89-
!IPAddress.IsLoopback(a));
64+
client.Dispose();
65+
throw new ConnectException(socketErrorCode);
66+
}
9067

91-
return ip ?? throw new Exception("No network adapters with a valid IPv4 address found.");
68+
69+
internal static TcpClient Join(IPAddress remoteIP, int remotePort, onConnectHandler onConnect)
70+
{
71+
(TcpClient client, IPEndPoint remoteEP) = GetClientWithEndpoint(remoteIP, remotePort);
72+
try
73+
{
74+
Connect(client, remoteEP, onConnect);
75+
return client;
76+
}
77+
catch (SocketException se)
78+
{
79+
client.Dispose();
80+
throw new ConnectException(se.ErrorCode);
9281
}
82+
}
83+
84+
public static IPAddress GetLocalIPAddress()
85+
{
86+
var host = Dns.GetHostEntry(Dns.GetHostName());
87+
var ip = host.AddressList.FirstOrDefault(a =>
88+
a.AddressFamily == AddressFamily.InterNetwork
89+
&& !IPAddress.IsLoopback(a));
90+
91+
return ip ?? throw new Exception("No network adapters with a valid IPv4 address found.");
92+
}
9393

9494

95-
public static IPEndPoint? GetRemoteClientEndpoint(TcpClient client) =>
96-
client.Client.RemoteEndPoint as IPEndPoint;
95+
public static IPEndPoint? GetRemoteClientEndpoint(TcpClient client) =>
96+
client.Client.RemoteEndPoint as IPEndPoint;
9797

98-
public static IPEndPoint? GetLocalClientEndpoint(TcpClient client) => client.Client.LocalEndPoint as IPEndPoint;
98+
public static IPEndPoint? GetLocalClientEndpoint(TcpClient client) => client.Client.LocalEndPoint as IPEndPoint;
9999

100-
public static (string, int) FlattenIPEndpoint(IPEndPoint ipEndPoint) =>
101-
(ipEndPoint.Address.ToString(), ipEndPoint.Port);
102-
}
100+
public static (string, int) FlattenIPEndpoint(IPEndPoint ipEndPoint) =>
101+
(ipEndPoint.Address.ToString(), ipEndPoint.Port);
103102
}

0 commit comments

Comments
 (0)