public async void InitAsync() { try { cancelToken = new CancellationTokenSource(); await ConnectMS(cancelToken.Token); } catch (OperationCanceledException) { mainFrm.AddLog2List("Service : Message Service is stopped."); } }
private async Task ListenMS(CancellationToken token) { try { IPAddress address = IPAddress.Parse(Globals.settings.MS_LISTENER_IP); _msListenter = new TcpListener(address, Globals.settings.MS_LISTENER_PORT); _msListenter.Start(); isActive = true; _mainFrm.AddLog2List("Log Service : Message Log Server is now live."); btnControl(true); //token.ThrowIfCancellationRequested(); while (isActive) { TcpClient msClient = _msListenter.AcceptTcpClient(); token.ThrowIfCancellationRequested(); _msClientList.Add(msClient); Globals.mainFrm.AddLog2List("Log Service : Main Server connected now."); await HandleClient(msClient, _mainFrm, token); } Debug.WriteLine("Line Exited"); } //catch (OperationCanceledException) //{ // _msListenter.Stop(); // _mainFrm.AddLog2List("Log Service : Message Server Stopped."); // isActive = false; // btnControl(false); //} catch (Exception ex) { if (ex.InnerException is OperationCanceledException) { token.ThrowIfCancellationRequested(); } else { if (token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } else { Debug.WriteLine("Error : " + ex.Message); _mainFrm.AddLog2List("Log Service : Message Server error while starting."); isActive = false; btnControl(false); } } } }
public async void InitAsync() { try { cancelToken = new CancellationTokenSource(); _gamelogClientList = new List <TcpClient>(); await ListenZSGamelog(cancelToken.Token); } catch (OperationCanceledException) { _mainFrm.AddLog2List("Log Service : Gamelog Server is stopped."); cancelToken.Dispose(); btnControl(false); } }
private static async Task HandleClient(TcpClient client, MainFrm mainFrm, CancellationToken token) { try { int BUFFER_SIZE = 4096; TcpClient tcpClient = client; byte[] buffer = new byte[BUFFER_SIZE]; String data = null; using NetworkStream ns = tcpClient.GetStream(); string message = null; int bytesReceivedMessage = 0; while (true) { token.ThrowIfCancellationRequested(); try { bytesReceivedMessage = await ns.ReadAsync(buffer, 0, buffer.Length); } catch (System.Exception) { break; } if (bytesReceivedMessage == 0) { //the client has disconnected from the server break; } //byte[] recBuf = new byte[bytesReceivedMessage]; //Array.Copy(buffer, recBuf, bytesReceivedMessage); message = Encoding.Default.GetString(buffer); Debug.WriteLine("Received: {0}", message); LogIdentificationService.Log(message); message = null; bytesReceivedMessage = 0; token.ThrowIfCancellationRequested(); } mainFrm.AddLog2List("Log Service : Main Server Client disconnected."); tcpClient.Close(); } catch (Exception) { client.Close(); throw; } }