/// <summary> /// Initializes a new instance of the <see cref="ModbusServer"/> class. /// </summary> /// <param name="port">The port to listen. (Default: 502)</param> /// <param name="listenAddress">The ip address to bind on. (Default: <see cref="IPAddress.IPv6Any"/>)</param> /// <param name="logger"><see cref="ILogger"/> instance to write log entries. (Default: no logger)</param> /// <param name="requestHandler">Set this request handler to override the default implemented handling. (Default: serving the data provided by Set* methods)</param> public ModbusServer(int port = 502, IPAddress listenAddress = null, ILogger logger = null, ModbusTcpRequestHandler requestHandler = null) { ListenAddress = listenAddress; if (ListenAddress == null) { ListenAddress = IPAddress.IPv6Any; } if (port < 0 || port > 65535) { throw new ArgumentOutOfRangeException(nameof(port)); } try { var listener = new TcpListener(ListenAddress, port); listener.Start(10); Port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); } catch (Exception ex) { throw new ArgumentException(nameof(port), ex); } this.logger = logger; this.requestHandler = requestHandler ?? HandleRequest; Initialization = Task.Run(() => Initialize()); }
public void StartMultiUnit(IPEndPoint localEndpoint) { var tcpClientProvider = new DefaultTcpClientProvider(localEndpoint); base.StopProcessing(); base.StartProcessing(); var requestHandlers = new List <ModbusTcpRequestHandler>(); // accept clients asynchronously /* https://stackoverflow.com/questions/2782802/can-net-task-instances-go-out-of-scope-during-run */ Task.Run(async() => { while (!this.CTS.IsCancellationRequested) { // There are no default timeouts (SendTimeout and ReceiveTimeout = 0), // use ConnectionTimeout instead. var tcpClient = await tcpClientProvider.AcceptTcpClientAsync(); var requestHandler = new ModbusTcpRequestHandler(tcpClient, this, handleUnitIdentifiers: true); lock (this.Lock) { if (this.MaxConnections > 0 && /* request handler is added later in 'else' block, so count needs to be increased by 1 */ this.RequestHandlers.Count + 1 > this.MaxConnections) { tcpClient.Close(); } else { this.RequestHandlers.Add(requestHandler); } } } }, this.CTS.Token); }