private static void ReadCallback(IAsyncResult ar) 
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state = (StateObject) ar.AsyncState;
            Socket handler = state.workSocket;

            // Read data from the client socket. 
            int bytesRead = handler.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));

                // Check for end-of-file tag. If it is not there, read 
                // more data.
                content = state.sb.ToString();
                if (content.IndexOf(_endOfRequestString) > -1) {
                    // All the data has been read from the client.
                    // Raise an event in order to get a response for the client.
                    var eventArgs = new RequestReceivedEventArgs(content);
                    RaiseRequestReceived(eventArgs);
                    // Whoever subscribed needs to populate the response of the RequestReceivedEventArgs
                    Send(handler, eventArgs.Response);
                } else {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
                }
            }
        }
 private static void RaiseRequestReceived(RequestReceivedEventArgs request)
 {
     var handler = RequestReceived;
     if (handler != null)
     {
         handler(null, request);
     }
 }
Example #3
0
        static void Server_RequestReceived(object sender, RequestReceivedEventArgs e)
        {
            Console.WriteLine("Service received a request:");
            Console.WriteLine(e.Request);

            logServerMessage("Recieving service request :", e.Request);

            var response = HandleRequest(e.Request);
            Console.WriteLine("Service responding with:");
            Console.WriteLine(response);
            e.Response = response;

            logServerMessage("Responding to service request  :", e.Response);
        }