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(); } } }
private async void BackgroundTaskEntryPoint() { while (!this.cancellationTokenSource.IsCancellationRequested) { PlcClient client = await this.plcServer.AcceptAsync().ConfigureAwait(false); client.OnClosed += (sender, _) => { var c = (PlcClient)sender; lock (this.lockObject) { this.clients.Remove(c); } this.Dispatcher.Invoke(() => { this.LogMessage(string.Format( CultureInfo.CurrentCulture, "PLC {0} 已断开连接。", c.RemoteEndPoint)); }); }; lock (this.lockObject) { if (this.clients.Count == 0) { client.OnDebugSending += (sender, bytes) => { this.Dispatcher.Invoke(() => { this.SendingDocument.Blocks.Clear(); this.SendingDocument.Blocks.Add(new Paragraph(new Run(HexUtils.Dump( bytes, bytesPerLine: 4, showHeader: false)))); }); }; client.OnDebugReceiving += (sender, bytes) => { this.Dispatcher.Invoke(() => { this.ReceivingDocument.Blocks.Clear(); this.ReceivingDocument.Blocks.Add(new Paragraph(new Run(HexUtils.Dump( bytes, bytesPerLine: 4, showHeader: false)))); }); }; this.clients.Add(client); } else { this.Dispatcher.Invoke(() => { this.LogMessage("测试程序只允许一台 PLC 连接。"); }); client.Close().ConfigureAwait(false).GetAwaiter().GetResult(); } } this.Dispatcher.Invoke(() => { this.LogMessage(string.Format( CultureInfo.CurrentCulture, "PLC {0} 已连接,点击按钮向 PLC 发送消息,鼠标悬停在按钮上有相关说明。", client.RemoteEndPoint)); }); } }