private void OnClientConnect(IAsyncResult asyncResult)
        {
            try
            {
                HttpListener listener = (HttpListener)asyncResult.AsyncState;
                executorHasClient = true;

                // Here we complete/end the BeginGetContext() asynchronous call
                // by calling EndGetContext() - which returns the reference to
                // a new HttpListenerContext object. Then we can set up a new
                // thread to listen for the next connection.
                HttpListenerContext workerContext = listener.EndGetContext(asyncResult);
                IAsyncResult        newResult     = listener.BeginGetContext(new AsyncCallback(OnClientConnect), listener);

                ExtensionRequestPacket packet = new ExtensionRequestPacket(workerContext);

                // Console.WriteLine("ID {0} connected.", packet.ID);
                if (packet.PacketType == ChromeExtensionPacketType.Get)
                {
                    // Console.WriteLine("Received GET request from from {0}", packet.ID);
                    Send(packet, HostPageHtml, "text/html");
                }
                else
                {
                    // Console.WriteLine("Received from {0}:\n{1}", packet.ID, packet.Content);
                    // pendingRequestQueue.Enqueue(packet);
                    pendingRequestQueue.Add(packet);
                    postRequestReceived.Set();
                }

                // Console.WriteLine("ID {0} disconnected.", packet.ID);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                Console.WriteLine("ERROR:" + se.Message);
            }
            catch (HttpListenerException hle)
            {
                // When we shut the HttpListener down, there will always still be
                // a thread pending listening for a request. If there is no client
                // connected, we may have a real problem here.
                if (!executorHasClient)
                {
                    Console.WriteLine(hle.Message);
                }
            }
        }
        private void Send(ExtensionRequestPacket packet, string data, string sendAsContentType)
        {
            if (packet.PacketType == ChromeExtensionPacketType.Post)
            {
                // Console.WriteLine("Sending to {0}:\n{1}", packet.ID, data);
                // Reset the signal so that the processor will wait for another
                // POST message.
                postRequestReceived.Reset();
            }

            byte[] byteData = Encoding.UTF8.GetBytes(data);
            HttpListenerResponse response = packet.Context.Response;

            response.KeepAlive         = true;
            response.StatusCode        = (int)HttpStatusCode.OK;
            response.StatusDescription = HttpStatusCode.OK.ToString();
            response.ContentType       = sendAsContentType;
            response.ContentLength64   = byteData.LongLength;
            response.Close(byteData, true);
        }
        private void SendMessage(Command commandToExecute)
        {
            // Wait for a POST request to be pending from the Chrome extension.
            // When one is received, get the packet from the queue.
            bool signalReceived = postRequestReceived.WaitOne(TimeSpan.FromSeconds(ExtensionTimeoutInSeconds));

            if (pendingRequestQueue.Count == 0)
            {
                throw new FatalChromeException("No pending requests from the extension in the queue");
            }

            // ExtensionRequestPacket packet = pendingRequestQueue.Dequeue();
            ExtensionRequestPacket packet = pendingRequestQueue[0];

            pendingRequestQueue.RemoveAt(0);

            // Get the parameter names to correctly serialize the command to JSON.
            commandToExecute.Parameters.Add("request", commandNameMap[commandToExecute.Name]);
            string commandStringToSend = commandToExecute.ParametersAsJsonString;

            // Send the response to the Chrome extension.
            Send(packet, commandStringToSend, "application/json; charset=UTF-8");
        }
        private Response HandleResponse()
        {
            // Wait for a POST request to be pending from the Chrome extension.
            // Note that we need to leave the packet in the queue for the next
            // send message.
            postRequestReceived.WaitOne(TimeSpan.FromSeconds(ExtensionTimeoutInSeconds));

            if (pendingRequestQueue.Count == 0)
            {
                throw new FatalChromeException("Expected a response from the extension, but none was found");
            }

            // ExtensionRequestPacket packet = pendingRequestQueue.Peek();
            ExtensionRequestPacket packet = pendingRequestQueue[0];

            // Parse the packet content, and deserialize from a JSON object.
            string   responseString = ParseResponse(packet.Content);
            Response response       = new Response();

            if (!string.IsNullOrEmpty(responseString))
            {
                response = JsonConvert.DeserializeObject <Response>(responseString);
                if (response.Status == WebDriverResult.Success)
                {
                    string valueAsString = response.Value as string;
                    if (valueAsString != null)
                    {
                        // First, collapse all \r\n pairs to \n, then replace all \n with
                        // System.Environment.NewLine. This ensures the consistency of
                        // the values.
                        response.Value = valueAsString.Replace("\r\n", "\n").Replace("\n", System.Environment.NewLine);
                    }
                }
            }

            return(response);
        }
Example #5
0
        private void Send(ExtensionRequestPacket packet, string data, string sendAsContentType)
        {
            if (packet.PacketType == ChromeExtensionPacketType.Post)
            {
                // Console.WriteLine("Sending to {0}:\n{1}", packet.ID, data);
                // Reset the signal so that the processor will wait for another
                // POST message.
                postRequestReceived.Reset();
            }

            byte[] byteData = Encoding.UTF8.GetBytes(data);
            HttpListenerResponse response = packet.Context.Response;
            response.KeepAlive = true;
            response.StatusCode = (int)HttpStatusCode.OK;
            response.StatusDescription = HttpStatusCode.OK.ToString();
            response.ContentType = sendAsContentType;
            response.ContentLength64 = byteData.LongLength;
            response.Close(byteData, true);
        }
Example #6
0
        private void OnClientConnect(IAsyncResult asyncResult)
        {
            try
            {
                HttpListener listener = (HttpListener)asyncResult.AsyncState;
                executorHasClient = true;

                // Here we complete/end the BeginGetContext() asynchronous call
                // by calling EndGetContext() - which returns the reference to
                // a new HttpListenerContext object. Then we can set up a new
                // thread to listen for the next connection.
                HttpListenerContext workerContext = listener.EndGetContext(asyncResult);
                IAsyncResult newResult = listener.BeginGetContext(new AsyncCallback(OnClientConnect), listener);

                ExtensionRequestPacket packet = new ExtensionRequestPacket(workerContext);

                // Console.WriteLine("ID {0} connected.", packet.ID);
                if (packet.PacketType == ChromeExtensionPacketType.Get)
                {
                    // Console.WriteLine("Received GET request from from {0}", packet.ID);
                    Send(packet, HostPageHtml, "text/html");
                }
                else
                {
                    // Console.WriteLine("Received from {0}:\n{1}", packet.ID, packet.Content);
                    // pendingRequestQueue.Enqueue(packet);
                    pendingRequestQueue.Add(packet);
                    postRequestReceived.Set();
                }

                // Console.WriteLine("ID {0} disconnected.", packet.ID);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                Console.WriteLine("ERROR:" + se.Message);
            }
            catch (HttpListenerException hle)
            {
                // When we shut the HttpListener down, there will always still be
                // a thread pending listening for a request. If there is no client
                // connected, we may have a real problem here.
                if (!executorHasClient)
                {
                    Console.WriteLine(hle.Message);
                }
            }
        }