OSDP.Net 5.2.1
A .NET library for implementing the Open Supervised Device Protocol (OSDP)
Loading...
Searching...
No Matches
TcpConnectionListener.cs
1using System;
2using System.Net.Sockets;
3using System.Threading.Tasks;
4using Microsoft.Extensions.Logging;
5
7
18{
19 private readonly TcpListener _listener;
20
28 int portNumber, int baudRate, ILoggerFactory loggerFactory = null) : base(baudRate, loggerFactory)
29 {
30 _listener = TcpListener.Create(portNumber);
31 }
32
34 public override Task Start(Func<IOsdpConnection, Task> newConnectionHandler)
35 {
36 if (IsRunning) return Task.CompletedTask;
37
38 IsRunning = true;
39 _listener.Start();
40
41 Logger?.LogInformation("TCP listener started on {Endpoint} for incoming OSDP connections", _listener.LocalEndpoint.ToString());
42
43 Task.Run(async () =>
44 {
45 while (IsRunning)
46 {
47 try
48 {
49 var client = await _listener.AcceptTcpClientAsync();
50 Logger?.LogDebug("Accepted TCP connection from {RemoteEndpoint}", client.Client.RemoteEndPoint?.ToString());
51
52 var connection = new TcpOsdpConnection(client, BaudRate, LoggerFactory);
53 var task = newConnectionHandler(connection);
54 RegisterConnection(connection, task);
55 }
56 catch (ObjectDisposedException)
57 {
58 // Expected when stopping the listener
59 break;
60 }
61 catch (Exception ex)
62 {
63 Logger?.LogError(ex, "Error accepting TCP connection");
64 }
65 }
66 });
67
68 return Task.CompletedTask;
69 }
70
72 public override Task Stop()
73 {
74 IsRunning = false;
75 _listener.Stop();
76 Logger?.LogInformation("TCP listener stopped");
77 return base.Stop();
78 }
79}
void RegisterConnection(OsdpConnection connection, Task task)
Registers a new connection and its associated handling task with the listener.
OsdpConnectionListener(int baudRate, ILoggerFactory loggerFactory=null)
Initializes a new instance of the OsdpConnectionListener class.
ILogger Logger
Gets the logger instance for this listener if a logger factory was provided.
bool IsRunning
Gets a value indicating whether the listener is currently running and accepting connections.
int BaudRate
Gets the baud rate for serial connections.For TCP connections, this value may not be applicable.
ILoggerFactory LoggerFactory
Gets the logger factory instance if one was provided during instantiation.
override Task Stop()
Stops the listener and terminates any active connections.A task representing the asynchronous operati...
override Task Start(Func< IOsdpConnection, Task > newConnectionHandler)
Starts listening for incoming connections from ACUs.A task representing the asynchronous operation.
TcpConnectionListener(int portNumber, int baudRate, ILoggerFactory loggerFactory=null)
Initializes a new instance of the TcpConnectionListener class.