-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
55 lines (50 loc) · 2.03 KB
/
Program.cs
File metadata and controls
55 lines (50 loc) · 2.03 KB
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
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ICLPrinterServer
{
internal class Program
{
private const int PORT_NUMBER = 4999;
private static async Task Main (string [] args)
{
Encoding.RegisterProvider (CodePagesEncodingProvider.Instance);
var listener = new TcpListener (IPAddress.Any, PORT_NUMBER);
listener.Start ();
var cts = new CancellationTokenSource ();
Console.WriteLine ($"Listening on port {PORT_NUMBER}");
Console.CancelKeyPress += (sender, e) =>
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine ("Ctrl+C pressed, stopping the listener...");
cts.Cancel ();
e.Cancel = true; // Prevent the application from terminating immediately
};
try {
while (!cts.IsCancellationRequested) {
var client = await listener.AcceptTcpClientAsync (cts.Token);
// Run each client connection asynchronously so we can accept new connections
_ = Task.Run (() => {
try {
new PrinterServer (client).Run ();
} catch (Exception ex) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine ($"Error handling client: {ex.Message}");
Console.ResetColor ();
}
});
}
} catch (OperationCanceledException) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine ("Operation cancelled.");
} finally {
listener.Stop ();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine ("Listener stopped.");
}
}
}
}