Пример #1
0
        private async void BackgroundTaskEntryPoint()
        {
            while (!this.cancellationTokenSource.IsCancellationRequested)
            {
                PlcClient client = null;
                try
                {
                    client = await this.plcServer.AcceptAsync().ConfigureAwait(false);

                    this.logger.LogInformation("TCP connection established from {0}", client.RemoteEndPoint);
                }
                catch (SocketException e)
                {
                    this.logger.LogError(e, "Failed to TCP accept PLC.");
                    continue;
                }
                catch (ObjectDisposedException)
                {
                    // Ignore it.
                    break;
                }

                ConnectResponse response;
                try
                {
                    response = await client
                               .ConnectAsync(new ConnectRequest(), DateTime.UtcNow.AddSeconds(10))
                               .ConfigureAwait(false);

                    this.logger.LogInformation(
                        "ConnectResponse received from newly PLC {0}: {1}",
                        client.RemoteEndPoint,
                        response);
                }
                catch (RpcException e)
                {
                    this.logger.LogWarning(
                        e,
                        "Failed to send ConnectRequest to newly PLC {0}, hang up.",
                        client.RemoteEndPoint);
                    await client.Close().ConfigureAwait(false);

                    client.Dispose();
                    continue;
                }

                client.OnClosed += (sender, args) =>
                {
                    this.logger.LogInformation(
                        "Client(MAC={0}, EndPoint={1}) disconnected.",
                        BitConverter.ToString(response.Id.ToByteArray()),
                        client.RemoteEndPoint);
                    this.PlcDictionary.TryRemove(response.Id, out PlcClient _);
                };

                if (this.PlcDictionary.TryAdd(response.Id, client))
                {
                    this.logger.LogInformation(
                        "Client(MAC={0}, EndPoint={1}) connected.",
                        BitConverter.ToString(response.Id.ToByteArray()),
                        client.RemoteEndPoint);
                }
                else
                {
                    this.logger.LogWarning(
                        "Failed to add the client(MAC={0}, EndPoint={1}) into dictionary.",
                        BitConverter.ToString(response.Id.ToByteArray()),
                        client.RemoteEndPoint);
                    await client.Close().ConfigureAwait(false);

                    client.Dispose();
                }
            }
        }