Instantly share code, notes, and snippets.

Embed
What would you like to do?
private void WaitForTcpClient(TcpListener listener)
{
while (true)
{
if (!ShouldStop && !listener.Pending())
{
Thread.Sleep(35);
}
else if (ShouldStop)
{
eventLogger.LogListenerInformation("Stopping the listener", port: listener.LocalEndpoint.ToString().GetPortNo());
listener.Stop();
}
else
{
try
{
eventLogger.LogListenerInformation("Waiting for new client", listener.LocalEndpoint.ToString().GetPortNo());
listener.BeginAcceptTcpClient(BeginListeningInBackground, listener);
}
catch (SocketException ex)
{
eventLogger.LogListenerError(ex);
listener.BeginAcceptTcpClient(BeginListeningInBackground, listener);
}
}
}
}
private void BeginListeningInBackground(IAsyncResult resultOfAsyncOperation)
{
UsingAsyncResultDo(resultOfAsyncOperation, async (asyncResult) =>
{
var listener = asyncResult.AsyncState as TcpListener;
var port = listener.LocalEndpoint.ToString().GetPortNo();
using (var tcpClient = listener.EndAcceptTcpClient(asyncResult))
{
if (tcpClient.Available > 0)
{
eventLogger.LogListenerInformation("Accepted client", port);
using (NetworkStream netStream = tcpClient.GetStream())
{
eventLogger.LogListenerInformation("Accepted client stream", port);
string filePath = Path.Combine(setting.TempFilesDirectory, GetFileName());
try
{
var bytes = new byte[tcpClient.ReceiveBufferSize];
netStream.Read(bytes, 0, tcpClient.ReceiveBufferSize);
string message = Encoding.ASCII.GetString(bytes).TrimStart('\v').TrimEnd('\0');
string msgControlId = await GetMessageControlIDFromMessageAsync(message);
await SendAcknowledgmentAsync(msgControlId, netStream, port);
tcpClient.Close();
using (StreamWriter streamWriter = new StreamWriter(filePath))
{
await streamWriter.WriteAsync(message);
}
await HandleAcknowledgedFileAsync(filePath, port);
}
catch (Exception ex)
{
eventLogger.LogListenerError(ex);
}
}
eventLogger.LogListenerInformation("Closing TCP Client", port);
}
else
{
eventLogger.LogListenerTelnetInformation(port);
}
}
});
}
private async Task SendAcknowledgmentAsync(string msgControlId, NetworkStream netStream, string port)
{
try
{
string ackMessage = await ackMessageGenerator.GenerateMessage(string.IsNullOrWhiteSpace(msgControlId) ? "AE" : "AA", msgControlId);
ackMessage = String.Format("{0}{1}{2}{3}", (char)0x0B, ackMessage, (char)0x1C, (char)0x0D);
try
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] sendingBuffer = encoder.GetBytes(ackMessage);
eventLogger.LogListenerInformation("Sending ACK message.", port);
await netStream.WriteAsync(sendingBuffer, 0, sendingBuffer.Length);
netStream.Flush();
}
catch (Exception)
{
eventLogger.LogListenerError("Error occured while sending acknowledgment message.", port);
}
}
catch (Exception)
{
eventLogger.LogListenerError("Error occured while creating acknowledgment message.", port);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment