/// <summary> /// This private method is the callback for the receive attempts. /// </summary> private void BytesReceived(IAsyncResult arg) { int byteCount; try { byteCount = socket.EndReceive(arg); } catch (Exception ex) { ReceiveRequest request = receiveQueue.Dequeue(); ThreadPool.QueueUserWorkItem((WaitCallback)(x => request.ReceiveBack((string)null, ex, request.Payload))); HandleReceiveQueue(); incomingLine = ""; return; } if (byteCount == 0) { linesReceivedQueue.Enqueue((string)null); HandleReceiveQueue(); } else { incomingLine = incomingLine + new string(incomingChars, 0, encoding.GetDecoder().GetChars(incomingBytes, 0, byteCount, incomingChars, 0, false)); int startIndex; int num; for (startIndex = 0; (num = incomingLine.IndexOf('\n', startIndex)) >= 0; startIndex = num + 1) { linesReceivedQueue.Enqueue(incomingLine.Substring(startIndex, num - startIndex)); } incomingLine = incomingLine.Substring(startIndex); HandleReceiveQueue(); } }
/// <summary> /// This helper method fulfils the requests (from queue) with the current /// available text and if more request are remaining to be handled, /// asks for more text via the socket. /// </summary> private void HandleReceiveQueue() { lock (receiveQueue) { while (receiveQueue.Count <ReceiveRequest>() > 0) { if (linesReceivedQueue.Count > 0) { string line = linesReceivedQueue.Dequeue(); ReceiveRequest request = receiveQueue.Dequeue(); ThreadPool.QueueUserWorkItem((WaitCallback)(x => request.ReceiveBack(line, (Exception)null, request.Payload))); } else { break; } } while (receiveQueue.Count > 0) { try { socket.BeginReceive(incomingBytes, 0, incomingBytes.Length, SocketFlags.None, new AsyncCallback(BytesReceived), (object)null); break; } catch (Exception ex) { ReceiveRequest request = receiveQueue.Dequeue(); ThreadPool.QueueUserWorkItem((WaitCallback)(x => request.ReceiveBack((string)null, ex, request.Payload))); incomingLine = ""; } } } }