Example #1
0
        /// <summary>
        /// Run after the server has acknowledged our receive request
        /// </summary>
        /// <param name="ar"></param>
        private static void ReceiveCallback(IAsyncResult ar)
        {
            string content = string.Empty;

            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state  = (StateObject)ar.AsyncState;
                Socket      client = state.WorkSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.Sb.Append(Encoding.ASCII.GetString(state.Buffer, 0, bytesRead));

                    content = state.Sb.ToString();

                    // Check for end-of-file tag. If it is not there, read
                    // more data.
                    if (content.IndexOf("<EOF>") > -1)
                    {
                        HandleData(content);

                        //Removes previous data received
                        state.DeleteData();
                    }

                    // Continue receiving
                    client.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.GetType().ToString() + e.Message);
            }
        }