Пример #1
0
 void WriteContextResponse(HttpContextAdapter adapter, int statusCode, string contentType, string payload, System.Text.Encoding encoding)
 {
     try
     {
         if (null == adapter)
         {
             return;
         }
         if (null == encoding)
         {
             encoding = Encoding;
         }
         if (null == contentType)
         {
             contentType = "text/plain";
         }
         adapter.ResponseContentType = contentType;
         byte[] binary = encoding.GetBytes(payload);
         adapter.OutputStream.Write(binary, 0, binary.Length);
         adapter.OutputStream.Close();
         //adapter.End();
     }
     catch
     {
         return;
     }
 }
Пример #2
0
        void ProcessJavascript(Guid loginToken, HttpContextAdapter adapter)
        {
            //Construct a response.
            string responseString = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"\resources\javascript\Classes\WebServerAPI.js").Replace("'<ServerObject>'", ToJSON());

            //Write response
            WriteContextResponse(adapter, 200, "text/javascript", responseString, Encoding);
        }
Пример #3
0
 /// <summary>
 /// Ends all ListenRequests
 /// </summary>
 internal void EndListenRequest()
 {
     lock (this)
     {
         EndRequest(HttpContext);
         HttpContext = null;
     }
 }
Пример #4
0
 void WriteContextResponseXml(HttpContextAdapter adapter, double xmlVersion, string rootNode, string xmlBody)
 {
     if (adapter == null)
     {
         return;
     }
     //Write the response
     WriteContextResponse(adapter, 200, "text/xml", CreateXmlPage(adapter.RemoteIPAddress.ToString(), xmlVersion, Encoding, rootNode, xmlBody), Encoding);
 }
Пример #5
0
 void WriteContextResponseHtml(HttpContextAdapter adapter, int statusCode, string responseHead, string responseTitle, string responseBody)
 {
     adapter.ResponseStatusCode  = statusCode;
     adapter.ResponseContentType = "text/html";
     byte[] binary = Encoding.GetBytes(CreateHtmlPage(adapter.RemoteIPAddress.ToString(), responseHead, responseTitle, responseBody));
     adapter.OutputStream.Write(binary, 0, binary.Length);
     adapter.OutputStream.Close();
     //adapter.End();
 }
Пример #6
0
        /// <summary>
        /// Accepts the Request
        /// </summary>
        /// <param name="state">HttpContext</param>
        internal void WorkerFunction(object state)
        {
            //If the state is not present then return
            if (null == state)
            {
                return;
            }
            //Create an HttpContext from the state
            HttpContextAdapter adapter = new HttpContextAdapter(state);
            //get the remoteIp
            IPAddress remoteIp = adapter.RemoteIPAddress;

            //If the RemoteEndPoint is Banned then Handle this scenario
            if (m_Banned.Contains(remoteIp))
            {
                ProcessBanned(adapter);
            }
            else
            {
                try
                {
                    //Get the loginToken from the request
                    Guid loginToken = adapter.GetLoginToken(m_Identifier);
                    if (loginToken.Equals(Guid.Empty))
                    {
                        throw new ArgumentException("loginToken");
                    }

                    //Determine the process
                    string process = Parts.SingleOrDefault(p => adapter.RequestUri.AbsoluteUri.Contains(p));

                    //Process the request according to the Determined ordinal
                    switch (process)
                    {
                    default: ProcessOther(loginToken, adapter); break;

                    case "Listen": ProcessListen(loginToken, adapter); break;

                    case "Send": ProcessSend(loginToken, adapter); break;

                    case "Info": ProcessInfo(loginToken, adapter); break;

                    case "Status": ProcessStatus(loginToken, adapter); break;

                    case "Javascript": ProcessJavascript(loginToken, adapter); break;
                    }
                }
                catch
                {
                    //There was an malformed loginToken
                    ProcessNoSession(adapter);
                }
            }

            //Poll workers and End the Listen Requests which have timed out from the Worker
            PollClients(true);
        }
Пример #7
0
        //All these methods are candidates to me be moved to the adapter


        void WriteContextResponseJson(HttpContextAdapter adapter, string functionName, string functionCode, string functionArguments)
        {
            //If there is no context then there is nothing we can do
            if (adapter == null)
            {
                return;
            }
            //Write response
            WriteContextResponse(adapter, 200, "text/javascript", CreateJavascriptFunction(functionName, functionCode, functionArguments), Encoding);
        }
Пример #8
0
        internal void BeginListenRequest(HttpContextAdapter context)
        {
            //Disconnect the current client
            EndListenRequest();

            //Increment state
            ListenId = Interlocked.Increment(ref ListenId);

            //Store the new listen
            HttpContext = context;
            HttpContext.BufferOutput        = true;
            HttpContext.ResponseContentType = "text/json";
            LastListen = DateTime.Now;
        }
Пример #9
0
        void ProcessOther(Guid loginToken, HttpContextAdapter adapter)
        {
            if (null == adapter)
            {
                return;
            }
            //Determine if the Uri matches a page in the custom sites
            string page = m_Sites.Keys.SingleOrDefault(p => adapter.RequestUri.AbsoluteUri.Contains(p));

            //If the page is not null then invoke the handler
            if (page != null)
            {
                //Get the handler Delegate from the Sites Dictionary
                Delegate handler = m_Sites[page];
                //If there is handler
                if (handler != null)
                {
                    //If the Delegate is a Relay or MessageHandler then Invoke it
                    if (handler is Relay)
                    {
                        ((Relay)handler).Invoke(loginToken, adapter);
                    }
                    else if (handler is MessageHandler)
                    {
                        ((MessageHandler)handler).Invoke(loginToken, adapter, null);
                    }
                    else
                    {
                        try
                        {
                            //The handler is a Delegate, try to Invoke it
                            handler.DynamicInvoke(new object[] { loginToken, adapter });
                        }
                        catch
                        {
                            //Throw the exception
                            throw;
                        }
                    }
                }
            }

            //Otherwise indicate the process is unknown
            ProcessUnknown(loginToken, adapter);
        }
Пример #10
0
        void ProcessDisconnect(Guid loginToken, HttpContextAdapter adapter)
        {
            WebClient client;

            //If we have a client
            if (m_Clients.TryGetValue(loginToken, out client))
            {
                //Inform the client of the Disconnect
                client.Que(CreateEnterExitMessage(client, true));

                //Push any message data at this time on the Response
                client.EndRequest(adapter);

                //Remove the Client from the Server
                RemoveClient(ref client);
            }
            else
            {
                //Indicate the client is not connected
                ProcessNoSession(adapter);
            }
        }
Пример #11
0
        void ProcessListen(Guid loginToken, HttpContextAdapter adapter)
        {
            WebClient client;

            //If we have a client
            if (m_Clients.TryGetValue(loginToken, out client))
            {
                //Being the ListenRequest
                client.BeginListenRequest(adapter);
            }
            else
            {
                //Create a client and being the ListenRequest
                client = new WebClient(loginToken, this);

                //Assign the application UserData
                client.UserData = new UserWrapper(client);

                //Ensure only one client is added in a listen
                lock (m_Clients)
                {
                    //Add the client o the m_Clients Dictionary
                    m_Clients.Add(client.LoginToken, client);
                }

                //Give the client the most up to date WebServerInfo
                client.Que(new WebMessage("webServerInfo", ToJSON()));

                //Instuct the client he is connected
                client.Que(CreateEnterExitMessage(client, false));

                //Begin his listenRequest
                client.BeginListenRequest(adapter);

                //Give the connected users to all users
                SendAll(CreateUserList());
            }
        }
Пример #12
0
        void ProcessInfo(Guid loginToken, HttpContextAdapter adapter)
        {
            //Construct a response.
            WebMessage message = new WebMessage("webServerInfo", ToJSON());

            //If we have a client then process the request as a message
            WebClient client;

            if (m_Clients.TryGetValue(loginToken, out client))
            {
                //Que the Information to the client
                client.Que(message);

                //End the request on the currentContext
                client.EndRequest(adapter);
            }
            else
            {
                //Write response
                WriteContextResponse(adapter, 200, "text/html", message.ToJSON(), Encoding);
                //WriteContextResponse(context, message.ToJSON(), "You have recieved the Server Information via JSON RPC, Please see the HEAD of this response!");
            }
        }
Пример #13
0
        internal void EndRequest(HttpContextAdapter adapter)
        {
            if (adapter == null)
            {
                return;
            }
            //Ensure there is only one thread working on this adapter
            lock (adapter)
            {
                //If there are messages to send, send them
                if (Messages.Count > 0)
                {
                    //Empty the volatile messages list into an array
                    WebMessage[] messages = Messages.ToArray();
                    Messages.Clear();

                    //Get the server encoding
                    Encoding encoding = Server.Encoding;

                    try
                    {
                        //FrameStart
                        adapter.OutputStream.WriteByte(encoding.GetBytes("[")[0]);
                    }
                    catch
                    {
                        //Reque the messages
                        Messages.AddRange(messages);
                        goto EndRequest;
                    }

                    byte[] binary;

                    //Get all of the messages except the last
                    if (messages.Length > 1)
                    {
                        //Iterate the array appending the JSON Object to the buffer
                        foreach (WebMessage message in messages.Take(Math.Max(1, messages.Length - 2)))
                        {
                            try
                            {
                                //Attempt to write the message
                                binary = encoding.GetBytes(message.ToJSON() + ',');
                                adapter.OutputStream.Write(binary, 0, binary.Length);
                            }
                            catch
                            {
                                //Reque the messages
                                Messages.Add(message);
                                continue;
                            }
                        }
                    }

                    //Get the last Message
                    WebMessage lastMessage = messages.Skip(messages.Length - 1).Take(1).Single();

                    try
                    {
                        //Attempt to write the lastMessage and FrameEnd
                        binary = encoding.GetBytes(lastMessage.ToJSON() + ']');
                        adapter.OutputStream.Write(binary, 0, binary.Length);
                    }
                    catch
                    {
                        //Reque the message
                        Messages.Add(lastMessage);
                        goto EndRequest;
                    }
                }

EndRequest:
                //End the current listen
                try
                {
                    adapter.OutputStream.Flush();
                    adapter.OutputStream.Close();
                    adapter.Close();
                    adapter.End();
                }
                catch
                {
                    return;
                }
            }
        }
Пример #14
0
        void ProcessSend(Guid loginToken, HttpContextAdapter adapter)
        {
            WebClient client;

            //If we have a client process the Send
            if (m_Clients.TryGetValue(loginToken, out client))
            {
                //Get the body data
                string body = adapter.GetRequestBody();

                //If there is body data decode and handle the incoming message
                if (!string.IsNullOrEmpty(body))
                {
                    try
                    {
                        //Use JavaScriptSerializer from System.Web.Extensions to Decode Message
                        Dictionary <string, object> message = Utilities.Serializer.DeserializeObject(body) as Dictionary <string, object>;
                        if (message != null)
                        {
                            //If we have a message determine the command
                            object value;
                            if (message.TryGetValue((String)message["Command"], out value))
                            {
                                //If we have a command attempt to process
                                string command = (String)value;
                                if (!string.IsNullOrEmpty(command))
                                {
                                    //Get the payload
                                    object payload;
                                    Dictionary <string, object> Payload = null;
                                    //If there was a payload unbox it
                                    if (message.TryGetValue("Payload", out payload))
                                    {
                                        Payload = payload as Dictionary <string, object>;
                                    }
                                    //Determine hook and process
                                    switch (command)
                                    {
                                    case "sendAll":
                                    {
                                        SendAll(new WebMessage(command, (String)message["Payload"]));
                                        return;
                                    }

                                    case "queAll":
                                    {
                                        QueAll(new WebMessage(command, (String)message["Payload"]));
                                        return;
                                    }

                                    case "sendToKey":
                                    {
                                        SendMessage((Guid)Payload["PublicKey"], new WebMessage(command, (String)Payload["Message"]));
                                        return;
                                    }

                                    case "queToKey":
                                    {
                                        QueMessage((Guid)Payload["PublicKey"], new WebMessage(command, (String)Payload["Message"]));
                                        return;
                                    }

                                    case "sendToChat":
                                    {
                                        break;
                                    }

                                    case "api":
                                    case "javascript":
                                    {
                                        ProcessJavascript(loginToken, adapter);
                                        return;
                                    }

                                    case "info":
                                    case "refresh":
                                    {
                                        ProcessInfo(loginToken, adapter);
                                        return;
                                    }

                                    case "status":
                                    {
                                        ProcessStatus(loginToken, adapter);
                                        return;
                                    }

                                    case "push":
                                    case "serverPush":
                                    {
                                        ProcessServerPush(loginToken, adapter);
                                        return;
                                    }

                                    default:
                                    {
                                        ProcessUnknown(loginToken, adapter);
                                        return;
                                    }
                                    }
                                }
                            }
                            else
                            {
                                ProcessOther(loginToken, adapter);
                                return;
                            }
                        }
                    }
                    catch
                    {
                        //Do nothing;
                    }
                }

                //Push any message data at this time on the Response
                client.EndRequest(adapter);
            }
            else
            {
                //Indicate the client is not connected
                ProcessNoSession(adapter);
            }
        }
Пример #15
0
 private void ProcessServerPush(Guid loginToken, HttpContextAdapter adapter)
 {
     throw new NotImplementedException();
 }
Пример #16
0
 void ProcessNoSession(HttpContextAdapter context)
 {
     //Write response
     WriteContextResponseHtml(context, 500, null, "Identification Error", string.Format("Sorry, Neither a HttpHeader or Cookie named '{0}' could be found that contained valid data identifying the session, please ensure the necessary data was passed in the request and try again.", m_Identifier));
 }
Пример #17
0
 void ProcessBanned(HttpContextAdapter context)
 {
     //Write response
     WriteContextResponseHtml(context, 500, null, "RemoteAddress Banned", "Sorry your IPAddress have been banned by the Administrator.");
 }
Пример #18
0
 void ProcessUnknown(Guid loginToken, HttpContextAdapter adapter)
 {
     //Write response with updated serverInfo
     WriteContextResponseHtml(adapter, 404, CreateJavascriptFunctionBlock(Anonymous, ToJSON(), null), "Error - 404", "The page you requested could not found, please try again!");//+ context.Request.Url.AbsoluteUri
 }
Пример #19
0
 void ProcessStatus(Guid loginToken, HttpContextAdapter context)
 {
     //TODO
 }