/// <summary> /// Processes a received message by looking for a newline character to satisfy a receive /// request. If no newlines are found and there are requests, asks for more data. /// </summary> private void ProcessReceivedMessage() { // Look for strings ending in a newline. while ((ReceivedMsg.Count() > 0 && ReceiveQueue.Count > 0)) { string line = ReceivedMsg.Dequeue(); ReceiveRequest rr = ReceiveQueue.Dequeue();//wrong? when do we do this? ThreadPool.QueueUserWorkItem(x => rr.receiveCallback(line, null, rr.payload)); } /////////////////////////////////////////////////////////////////// // If there is no newline and you have a request, call BeginReceive. while (ReceiveQueue.Count > 0) { try{ // Ask for some more data socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, MessageReceived, buffer); //not sure why Matt suggetest this break break; } catch (Exception e) { ReceiveRequest rr = ReceiveQueue.Dequeue(); //wrong? when do we do this? ThreadPool.QueueUserWorkItem(x => rr.receiveCallback(null, e, rr.payload)); incoming = ""; } } }
/// <summary> /// Called when some data has been received. /// /// Gets the bytes that were received, stores them in a string, and /// calls a method to process the received message. /// </summary> private void MessageReceived(IAsyncResult result) { // Protect the ReceiveQueue. lock (ReceiveQueue) { try { // Get the buffer to which the data was written. buffer = (byte[])(result.AsyncState); // Figure out how many bytes have come in. int bytes = socket.EndReceive(result); // If no bytes were received, close the socket. if (bytes == 0) { //socket.Close(); // Enqueue null message ReceivedMsg.Enqueue(null); // Call ProcessReceive ProcessReceivedMessage(); } // Otherwise, decode the incoming bytes, then process the message. else { // Decode the bytes, and append them to the 'incoming' string member variable. incoming += encoding.GetString(buffer, 0, bytes); // Extract messages ending with newlines and enqueue them ////////////////////////////////////////////////////////////////// // Look for strings ending in a newline. int index; while (((index = incoming.IndexOf('\n')) >= 0)) { // Get the first string ending in a newline. String line = incoming.Substring(0, index); ReceivedMsg.Enqueue(line); incoming = incoming.Substring(index + 1); } /////////////////////////////////////////////////////////////////////////////// ProcessReceivedMessage(); } } //Error occured catch (Exception e) { ReceiveRequest rr = ReceiveQueue.Dequeue(); ThreadPool.QueueUserWorkItem(x => rr.receiveCallback(null, e, rr.payload)); ProcessReceivedMessage(); incoming = ""; } } }