Ejemplo n.º 1
0
        /// <summary>
        /// Stop server
        /// </summary>
        public void Stop()
        {
            finalizeServer = true;

            LoggingMethod.WriteToLog("Stopping Server...", LoggingMethod.LevelInfo);

            try
            {
                listener.Stop();
            }
            catch
            {
            }

            try
            {
                trf.Abort();
            }
            catch
            {
            }

            trf = null;

            LoggingMethod.WriteToLog("Server was stoped.", LoggingMethod.LevelInfo);

            IsRunning = false;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Internal server listener
        /// </summary>
        private void ServerFunction()
        {
            LoggingMethod.WriteToLog("Starting Server...", LoggingMethod.LevelInfo);

Start:

            try
            {
                var ipEndPoint = new IPEndPoint(IPAddress.Any, uri.Port);
                listener = new TcpListener(ipEndPoint);

                listener.Start();

                while (true)
                {
                    var clientSocket = listener.AcceptSocket();

                    LoggingMethod.WriteToLog(String.Format("Client accepted: {0}", ((IPEndPoint)clientSocket.LocalEndPoint).ToString()), LoggingMethod.LevelInfo);

                    SocketInformation socketInfo = clientSocket.DuplicateAndClose(Process.GetCurrentProcess().Id);

                    Thread trfS = new Thread(new ParameterizedThreadStart((object obj) =>
                    {
                        string strData;
                        byte[] data = new byte[MAXBUFFER];

                        //var sock = (Socket)obj;
                        var sock            = new Socket((SocketInformation)obj);
                        SslStream sslStream = null;
                        Stream stream       = new NetworkStream(sock);

                        try
                        {
                            if (secure)
                            {
                                /////sslStream = new SslStream(stream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                                sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                                sslStream.AuthenticateAsServer(certificate, true, System.Security.Authentication.SslProtocols.Default, false);
                                strData = ReadMessage(sslStream);
                                stream  = sslStream;
                            }
                            else
                            {
                                strData = ReadMessage(stream);
                            }

                            ////try
                            ////{
                            ////    ////sslStream = new SslStream(stream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                            ////    sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                            ////    sslStream.AuthenticateAsServer(certificate, true, System.Security.Authentication.SslProtocols.Default, false);
                            ////    strData = ReadMessage(sslStream);
                            ////    stream = sslStream;
                            ////}
                            ////catch
                            ////{
                            ////    strData = ReadMessage(stream);
                            ////    strData = "GET /" + strData;
                            ////}

                            LoggingMethod.WriteToLog(String.Format("Request: {0}", strData), LoggingMethod.LevelVerbose);
                        }
                        catch (Exception error)
                        {
                            LoggingMethod.WriteToLog(String.Format("Error: {0}", error.Message), LoggingMethod.LevelError);
                            throw error;
                        }

                        string[] lines = strData.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                        string path    = lines[0].Substring(0, lines[0].LastIndexOf(" "));
                        responses.Add(path);
                        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("        ###  MM/dd/yyyy HH:mm:ss:fff") + " - " + path);

                        try
                        {
                            Request item = null;
                            try
                            {
                                item = requests[path];
                            }
                            catch
                            {
                                try
                                {
                                    item = requests[path.Substring(0, path.IndexOf("?"))];
                                }
                                catch
                                {
                                    item        = new MockServer.Request();
                                    item.Method = "GET";

                                    if (path.Contains("GET /v2/presence/") && !path.Contains("/leave?"))
                                    {
                                        item.Response   = "{\"t\":{\"t\":\"14844074079055214\",\"r\":7},\"m\":[]}";
                                        item.StatusCode = HttpStatusCode.OK;
                                    }
                                    else if (path.Contains("GET /v2/subscribe/"))
                                    {
                                        item.Response   = "{}";
                                        item.StatusCode = HttpStatusCode.OK;
                                    }
                                    else if (path.Contains("GET /time/0"))
                                    {
                                        item.Response   = "[14827611897607991]";
                                        item.StatusCode = HttpStatusCode.OK;
                                    }
                                    else if (path.Contains("/leave?"))
                                    {
                                        item.Response   = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}";
                                        item.StatusCode = HttpStatusCode.OK;
                                    }
                                    else if (path.Contains("GET /publish/"))
                                    {
                                        item.Response   = "[1,\"Sent\",\"14715322883933786\"]";
                                        item.StatusCode = HttpStatusCode.OK;
                                    }
                                    else
                                    {
                                        item.Response   = "";
                                        item.StatusCode = HttpStatusCode.OK;    //// HttpStatusCode.NotFound;
                                    }
                                }
                            }

                            LoggingMethod.WriteToLog(String.Format("Response: {0}", item.Response), LoggingMethod.LevelVerbose);

                            switch (item.StatusCode)
                            {
                            case HttpStatusCode.OK:
                                {
                                    string statusOK = "HTTP/1.1 200 OK\r\n";
                                    statusOK       += "Content-type: text/html\r\n";
                                    statusOK       += String.Format("Content-length: {0}\r\n\r\n", item.Response.Length.ToString());
                                    statusOK       += item.Response;
                                    stream.Write(System.Text.Encoding.UTF8.GetBytes(statusOK), 0, statusOK.Length);
                                    Thread.Sleep(10);

                                    break;
                                }

                            case HttpStatusCode.BadRequest:
                            default:
                                {
                                    string statusBadRequest = "HTTP/1.1 400 Bad Request\r\n";
                                    statusBadRequest       += "Content-type: text/html\r\n";
                                    statusBadRequest       += String.Format("Content-length: {0}\r\n\r\n", item.Response.Length.ToString());
                                    statusBadRequest       += item.Response;
                                    stream.Write(System.Text.Encoding.UTF8.GetBytes(statusBadRequest), 0, statusBadRequest.Length);
                                    Thread.Sleep(10);
                                    break;
                                }

                            case HttpStatusCode.Unauthorized:
                                break;

                            case HttpStatusCode.Forbidden:
                                break;

                            case HttpStatusCode.NotFound:
                                {
                                    string statusNotFound = "HTTP/1.1 404 Not Found\r\n";
                                    statusNotFound        = "HTTP/1.1 404 Not Found\r\n";
                                    statusNotFound       += "Content-type: text/html\r\n";
                                    statusNotFound       += String.Format("Content-length: {0}\r\n\r\n", item.Response.Length.ToString());
                                    statusNotFound       += item.Response;
                                    stream.Write(System.Text.Encoding.UTF8.GetBytes(statusNotFound), 0, statusNotFound.Length);
                                    Thread.Sleep(10);
                                    break;
                                }
                            }
                        }
                        catch (Exception eHttp)
                        {
                            LoggingMethod.WriteToLog(String.Format("Path not found: {0}", strData), LoggingMethod.LevelError);
                            string statusNotFound = "HTTP/1.1 404 Not Found\r\n";
                            statusNotFound        = "HTTP/1.1 404 Not Found\r\n";
                            statusNotFound       += "Content-type: text/html\r\n";
                            statusNotFound       += String.Format("Content-length: {0}\r\n\r\n", notFoundContent.Length.ToString());
                            statusNotFound       += notFoundContent;
                            stream.Write(System.Text.Encoding.UTF8.GetBytes(statusNotFound), 0, statusNotFound.Length);
                            Thread.Sleep(10);
                        }

                        if (sslStream != null)
                        {
                            sslStream.Flush();
                            sslStream.Close();
                        }

                        stream.Flush();
                        stream.Close();
                        clientSocket.Close();
                    }));

                    trfS.IsBackground = true;
                    trfS.SetApartmentState(ApartmentState.MTA);

                    trfS.Start(socketInfo);
                }
            }
            catch (Exception error)
            {
                if (!finalizeServer)
                {
                    LoggingMethod.WriteToLog(String.Format("Error: {0}", error.Message), LoggingMethod.LevelVerbose);
                    listener.Stop();
                    goto Start;
                }
            }
        }