Esempio n. 1
0
		private static void FormatJsonResponse(HttpListenerResponse response, string version, string status, string timestamp)
		{
			try
			{
				response.StatusCode = 200;
				response.StatusDescription = "OK";
				response.ContentType = "application/json";

				var messageBuffer = new StringBuilder();
				messageBuffer.Append("{ \"version\": \"");
				messageBuffer.Append(version);
				messageBuffer.Append("\", \"status\": \"");
				messageBuffer.Append(status);
				messageBuffer.Append("\", \"timestamp\": \"");
				messageBuffer.Append(timestamp);
				messageBuffer.Append("\" }");

				byte[] binaryPayload = Encoding.UTF8.GetBytes(messageBuffer.ToString());
				response.ContentLength64 = binaryPayload.LongLength;
				response.OutputStream.Write(binaryPayload, 0, binaryPayload.Length);
			}
			finally
			{
				response.Close();
			}
		}
		private static async Task ServeDirectoryListingAsync(DirectoryInfo root, DirectoryInfo directory, HttpListenerResponse response)
		{
			StringBuilder listBuilder = new StringBuilder();

			foreach (FileInfo file in directory.EnumerateFiles())
			{
				String target = directory.IsSameDirectory(root) ? file.Name
				                                                : Path.Combine(directory.Name, file.Name);
				listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, file.Name);
			}

			foreach (DirectoryInfo subDirectory in directory.EnumerateDirectories())
			{
				String target = directory.IsSameDirectory(root) ? subDirectory.Name
				                                                : Path.Combine(directory.Name, subDirectory.Name);
				listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, subDirectory.Name);
			}

			String htmlResponse = String.Format("<ul>{0}</ul>", listBuilder.ToString());

			response.ContentType = "text/html";
			response.ContentLength64 = htmlResponse.Length;
			response.AddHeader("Date", DateTime.Now.ToString("r"));

			response.StatusCode = (Int32)HttpStatusCode.OK; // Must be set before writing to OutputStream.

			using (StreamWriter writer = new StreamWriter(response.OutputStream))
			{
				await writer.WriteAsync(htmlResponse).ConfigureAwait(false);
			}
		}
Esempio n. 3
0
        public Response(HttpListenerResponse response, App app)
        {
            _response = response;
            _writer = new StreamWriter(new BufferedStream(response.OutputStream));

            App = app;
        }
 public HttpListenerWebConnection(IWebServer webServer, HttpListenerContext context)
     : base(webServer, CallingFrom.Web)
 {
     Context = context;
     Request = Context.Request;
     Response = Context.Response;
 }
Esempio n. 5
0
 public ListenerResponse(HttpListenerResponse response, IRequest request = null)
 {
     this.response = response;
     this.Request  = request;
     this.Cookies  = new Cookies(this);
     this.Items    = new Dictionary <string, object>();
 }
Esempio n. 6
0
 private void RespondWithNotFound(HttpListenerRequest request, HttpListenerResponse response)
 {
     _log.DebugFormat("Responded with 404 Not Found for url {0}", request.Url);
     response.StatusCode = 404;
     response.StatusDescription = "Not Found";
     response.OutputStream.Close();
 }
Esempio n. 7
0
 public API(ref HttpListenerContext context, Server myServer)
 {
     this.QS = context.Request.QueryString;
     this.Request = context.Request;
     this.Response = context.Response;
     this.Method = new APIMethod(ref this.QS);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpListenerResponseAdapter" /> class.
        /// </summary>
        /// <param name="Response">The <see cref="HttpListenerResponse" /> to adapt for WebDAV#.</param>
        /// <exception cref="System.ArgumentNullException">Response</exception>
        /// <exception cref="ArgumentNullException"><paramref name="Response" /> is <c>null</c>.</exception>
        public HttpListenerResponseAdapter(HttpListenerResponse Response)
        {
        if (Response == null)
            throw new ArgumentNullException("Response");

        _response = Response;
        }
Esempio n. 9
0
 private void request_handler(HttpListenerResponse handler_response, HttpListenerRequest handler_request)
 {
     string document = handler_request.RawUrl;
     string docpath = root_path + document;
     byte[] responsebyte;
     if (File.Exists(docpath))
     {
         handler_response.StatusCode = (int)HttpStatusCode.OK;
         handler_response.ContentType = "text/html";
         responsebyte = File.ReadAllBytes(docpath);
     }
     else
     {
         if (debug)
         {
             handler_response.StatusCode = (int)HttpStatusCode.NotFound;
             string responsestring = "Server running! ";
             responsestring += "document: " + document + " ";
             responsestring += "documentpath: " + docpath + " ";
             responsestring += "root_path " + root_path + " ";
             responsebyte = System.Text.Encoding.UTF8.GetBytes(responsestring);
         }
         else
         {
             handler_response.StatusCode = (int)HttpStatusCode.NotFound;
             handler_response.ContentType = "text/html";
             responsebyte = File.ReadAllBytes(root_path + "//error//error.html");
         }
     }
     handler_response.ContentLength64 = responsebyte.Length;
     System.IO.Stream output = handler_response.OutputStream;
     output.Write(responsebyte, 0, responsebyte.Length);
     output.Close();
 }
 private static void WriteResponseDto(HttpListenerResponse response, ISerializer serializer, MyDummyResponse responseDto)
 {
     using (var writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
     {
         serializer.Serialize(writer, responseDto);
     }
 }
Esempio n. 11
0
 public ResponseInstance(ScriptEngine engine, HttpListenerResponse response)
     : base(engine)
 {
     this.Response = response;
     this.PopulateFields();
     this.PopulateFunctions();
 }
Esempio n. 12
0
        /// <summary>
        /// http响应
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="response"></param>
        /// <param name="type"></param>
        public void ResponseWrite(string msg, System.Net.HttpListenerResponse response, string type = "text/plain")
        {
            try
            {
                //使用Writer输出http响应代码
                if (type == "text/plain")
                {
                    //using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.OutputStream, new UTF8Encoding()))
                    //{
                    //    response.ContentType = type + ";charset=utf-8";
                    //    writer.WriteLine(msg);
                    //    writer.Close();
                    //    response.Close();
                    //}
                }

                using (StreamWriter writer = new StreamWriter(response.OutputStream))
                {
                    response.StatusCode = 200;
                    response.Headers.Add("Access-Control-Allow-Origin", "*");
                    response.ContentType     = "application/json";
                    response.ContentEncoding = Encoding.UTF8;

                    writer.WriteLine(msg);
                    writer.Close();
                    response.Close();
                }
            }
            catch (Exception exception)
            {
            }
        }
        public override void GetNodesInfoHandler(GetNodesInfoRequest request, System.Net.HttpListenerResponse response)
        {
            var writers = Enumerable.Range(0, Global.CloudStorage.PartitionCount).Select(i => new GetNodesInfoRequestWriter(fields: new List <string> {
                "type_object_name"
            })).ToArray();

            foreach (var id in request.ids)
            {
                writers[Global.CloudStorage.GetPartitionIdByCellId(id)].ids.Add(id);
            }

            var readers = writers.Select((writer, server) => _GetNodesInfo_impl(server, writer)).ToArray();

            var results = readers.Aggregate(
                (IEnumerable <NodeInfo>) new List <NodeInfo>(),
                (_, reader) =>
                Enumerable.Concat(_, reader.infoList.Select(infoAccessor => (NodeInfo)infoAccessor)));

            string result_string = "[" + string.Join(",", results.Select(_ =>
                                                                         string.Format(CultureInfo.InvariantCulture, @"{{""CellID"": {0}, ""type_object_name"": {1}}}",
                                                                                       _.id,
                                                                                       JsonStringProcessor.escape(_.values.First())))) + "]";

            using (var sw = new StreamWriter(response.OutputStream))
            {
                sw.Write(result_string);
            }
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="HttpListenerResponseAdapter" /> class.
        /// </summary>
        /// <param name="response">The <see cref="HttpListenerResponse" /> to adapt for WebDAV#.</param>
        /// <exception cref="System.ArgumentNullException">Response</exception>
        /// <exception cref="ArgumentNullException"><paramref name="response" /> is <c>null</c>.</exception>
        public HttpListenerResponseAdapter(HttpListenerResponse response)
        {
            if (response == null)
                throw new ArgumentNullException(nameof(response));

            _response = response;
        }
Esempio n. 15
0
 /// <summary>
 /// Выполняет приложение
 /// Для запросов GET возвращает все записи.
 /// Для запросов POST создает и сохраняет новые записи.
 /// </summary>
 /// <param name="request">Request.</param>
 /// <param name="response">Response.</param>
 public override void Run(HttpListenerRequest request, HttpListenerResponse response)
 {
     if (request.HttpMethod == "POST")
     {
         if (request.HasEntityBody)
         {
             // читаем тело запроса
             string data = null;
             using (var reader = new StreamReader(request.InputStream))
             {
                 data = reader.ReadToEnd ();
             }
             if (!string.IsNullOrWhiteSpace(data))
             {
                 // формируем коллекцию параметров и их значений
                 Dictionary<string, string> requestParams = new Dictionary<string, string>();
                 string[] prms = data.Split('&');
                 for (int i = 0; i < prms.Length; i++)
                 {
                     string[] pair = prms[i].Split('=');
                     requestParams.Add(pair[0], Uri.UnescapeDataString(pair[1]).Replace('+',' '));
                 }
                 SaveEntry (GuestbookEntry.FromDictionary(requestParams));
             }
             response.Redirect(request.Url.ToString());
             return;
         }
     }
     DisplayGuestbook (response);
 }
Esempio n. 16
0
        private void ResponseException(
            string method, string path, Exception ex, ISession session, HttpListenerResponse response)
        {
            string body = null;
            var httpStatus = HttpStatusCode.InternalServerError;
            string contentType = "application/json";

            if (ex is FailedCommandException)
            {
                var message = new Dictionary<string, object>
                {
                    { "sessionId", (session != null ? session.ID : null) },
                    { "status", ((FailedCommandException)ex).Code },
                    { "value", new Dictionary<string, object>
                        {
                            { "message", ex.Message } // TODO stack trace
                        }
                    }
                };

                body = JsonConvert.SerializeObject(message);
            }
            else
            {
                httpStatus = HttpStatusCode.BadRequest;
                contentType = "text/plain";
                body = ex.ToString();
            }

            this.WriteResponse(response, httpStatus, contentType, body);
        }
Esempio n. 17
0
 public static void ResponseWrite(HttpListenerResponse response, string content)
 {
     using (StreamWriter sw = new StreamWriter(response.OutputStream))
     {
         sw.Write(content);
     }
 }
 private void SendHttpResponse(TcpClient client, Stream stream, HttpListenerResponse response, byte[] body)
 {
     // Status line
     var statusLine = $"HTTP/1.1 {response.StatusCode} {response.StatusDescription}\r\n";
     var statusBytes = Encoding.ASCII.GetBytes(statusLine);
     stream.Write(statusBytes, 0, statusBytes.Length);
     // Headers
     foreach (var key in response.Headers.AllKeys)
     {
         var value = response.Headers[key];
         var line = $"{key}: {value}\r\n";
         var lineBytes = Encoding.ASCII.GetBytes(line);
         stream.Write(lineBytes, 0, lineBytes.Length);
     }
     // Content-Type header
     var contentType = Encoding.ASCII.GetBytes($"Content-Type: {response.ContentType}\r\n");
     stream.Write(contentType, 0, contentType.Length);
     // Content-Length header
     var contentLength = Encoding.ASCII.GetBytes($"Content-Length: {body.Length}\r\n");
     stream.Write(contentLength, 0, contentLength.Length);
     // "Connection: close", to tell the client we can't handle persistent TCP connections
     var connection = Encoding.ASCII.GetBytes("Connection: close\r\n");
     stream.Write(connection, 0, connection.Length);
     // Blank line to indicate end of headers
     stream.Write(new[] { (byte)'\r', (byte)'\n' }, 0, 2);
     // Body
     stream.Write(body, 0, body.Length);
     stream.Flush();
     // Graceful socket shutdown
     client.Client.Shutdown(SocketShutdown.Both);
     client.Dispose();
 }
Esempio n. 19
0
 public BrowserSender(HttpListenerContext context)
 {
     Context = context;
     Request = context.Request;
     Response = context.Response;
     User = context.User;
 }
Esempio n. 20
0
        public void HandleGet(HttpListenerRequest request, HttpListenerResponse response)
        {
            string queryString = request.Url.Query;
            var queryParts = Server.ParseQueryString(queryString);

            string presetName = queryParts.GetFirstValue("preset");

            if (string.IsNullOrEmpty(presetName))
            {
                response.StatusCode = 200;
                response.WriteResponse(presets.GetAll());
            }
            else
            {
                string result = presets.Get(presetName);
                if (result == null)
                {
                    response.StatusCode = 404;
                    response.WriteResponse("No such preset has been registered");
                }
                else
                {
                    response.StatusCode = 200;
                    response.WriteResponse(result);
                }
            }
        }
Esempio n. 21
0
 public override object Handle(Project project, object body, HttpListenerResponse response)
 {
     return project
         .GetVersions()
         .OrderByDescending(v => v)
         .FirstOrDefault();
 }
Esempio n. 22
0
        /// <summary>
        /// Construct new ServerThread, using HttpListenerContext to populate request and response objects
        /// </summary>
        /// <param name="context">The HttpListenerContext of the current request</param>
        public HttpServerThread(HttpListenerContext context)
        {
            _request = context.Request;
            _response = context.Response;

            Output.Write(Name + " initialised");
        }
Esempio n. 23
0
        private static bool PuppetProcessor(HttpListenerRequest request, HttpListenerResponse response)
        {
            string content = null;
            if (request.HttpMethod == "GET")
            {
                var contentId = request.QueryString.Count > 0 ? request.QueryString[0] : null;
                if (string.IsNullOrEmpty(contentId) || !_contentStore.ContainsKey(contentId))
                {
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                    return false;
                }

                content = _contentStore[contentId]??"";
            }
            else
            {
                if (request.HasEntityBody)
                {
                    using (var sr = new StreamReader(request.InputStream))
                    {
                        content = sr.ReadToEnd();
                    }
                }
                //response.ContentType = "application/json";
            }

            byte[] buf = Encoding.UTF8.GetBytes(content);
            response.ContentLength64 = buf.Length;
            response.OutputStream.Write(buf, 0, buf.Length);
            return true;
        }
 public HttpListenerResponse(HttpListenerCommunicationContext context, System.Net.HttpListenerResponse response)
 {
     _context        = context;
     _nativeResponse = response;
     Headers         = new HttpHeaderDictionary();
     Entity          = new HttpEntity(Headers, response.OutputStream);
 }
Esempio n. 25
0
        static void GetFileHandler(HttpListenerRequest request, HttpListenerResponse response)
        {
            var query = request.QueryString;
            string targetLocation = query["target"];
            Log ("GetFile: " + targetLocation + "...");

            if(File.Exists(targetLocation))
            {
                try
                {
                    using(var inStream = File.OpenRead(targetLocation))
                    {
                        response.StatusCode = 200;
                        response.ContentType = "application/octet-stream";
                        CopyStream(inStream, response.OutputStream);
                    }
                }
                catch(Exception e)
                {
                    Log (e.Message);
                    response.StatusCode = 501;
                }
            }
            else
            {
                response.StatusCode = 501;
                Log ("File doesn't exist");
            }
        }
Esempio n. 26
0
 public override void Process(HttpListenerRequest request, HttpListenerResponse response)
 {
     using (var stream = typeof(StaticHandler).Assembly.GetManifestResourceStream("SongRequest.Static.favicon.ico"))
     {
         stream.CopyTo(response.OutputStream);
     }
 }
Esempio n. 27
0
		/**
		 * Respond with current JSON data.
		 */
		void SendResponse(HttpListenerResponse response, string message)
		{
			byte[] buffer = Encoding.UTF8.GetBytes(message);
			response.ContentLength64 = buffer.Length;
			using (Stream output = response.OutputStream)
				output.Write(buffer, 0, buffer.Length);
		}
        public HttpEntity(DateTime timeStamp,
                          ICodec requestCodec,
                          ICodec responseCodec,
                          HttpListenerContext context,
                          string[] allowedMethods,
                          Action<HttpEntity> onRequestSatisfied)
        {
            Ensure.NotNull(requestCodec, "requestCodec");
            Ensure.NotNull(responseCodec, "responseCodec");
            Ensure.NotNull(context, "context");
            Ensure.NotNull(allowedMethods, "allowedMethods");
            Ensure.NotNull(onRequestSatisfied, "onRequestSatisfied");

            TimeStamp = timeStamp;
            UserHostName = context.Request.UserHostName;

            RequestCodec = requestCodec;
            ResponseCodec = responseCodec;
            _context = context;

            Request = context.Request;
            Response = context.Response;

            Manager = new HttpEntityManager(this, allowedMethods, onRequestSatisfied);
        }
Esempio n. 29
0
		public void Process(HttpListenerRequest request, HttpListenerResponse response)
		{
			try
			{
				if (request.HttpMethod != "GET")
				{
					response.StatusCode = 405;
					response.StatusDescription = "Method Not Supported";
					response.Close();
					return;
				}

				string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;
				string status = GetStatusDescription();
				string timestamp = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "Z";

				FormatJsonResponse(response, version, status, timestamp);
			}
			catch (HttpListenerException hlex)
			{
				Supervisor.LogException(hlex, TraceEventType.Error, request.RawUrl);

				response.StatusCode = 500;
				response.StatusDescription = "Error Occurred";
				response.Close();
			}
		}
Esempio n. 30
0
        void RequestHandler(HttpListenerRequest req, HttpListenerResponse res)
        {
            Console.WriteLine("[RequestHandler: req.url=" + req.Url.ToString());

            if (req.Url.AbsolutePath == "/cmd/record/start") {
                Record.Start(req, res);
            }
            else if (req.Url.AbsolutePath == "/cmd/record/stop") {
                Record.Stop(req, res);
            }
            else if (req.Url.AbsolutePath == "/cmd/livingcast/start") {
                LivingCast.Start(req, res);
            }
            else if (req.Url.AbsolutePath == "/cmd/livingcast/stop") {
                LivingCast.Stop(req, res);
            }
            else {
                res.StatusCode = 404;
                res.ContentType = "text/plain";

                try
                {
                    StreamWriter sw = new StreamWriter(res.OutputStream);
                    sw.WriteLine("NOT supported command: " + req.Url.AbsolutePath);
                    sw.Close();
                }
                catch { }
            }
        }
Esempio n. 31
0
 public override void WriteTo(HttpListenerResponse resp)
 {
     base.WriteTo(resp);
     FileStream fs = new FileStream(_file, FileMode.Open);
     fs.CopyTo(resp.OutputStream);
     fs.Close();
 }
Esempio n. 32
0
        /// <summary>
        /// handle left clicks from client
        /// </summary>
        /// <param name="response"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public override byte[] HandleRequest(HttpListenerResponse response, string[] uri)
        {
            // must have 5 tokens
            if (uri.Length != 7)
            {
                response.StatusCode = 400;
                return BuildHTML("Error...");
            }

            int screen = GetRequestedScreenDevice(uri, screens);

            bool error = handleMouseDown(uri, screen);
            if (error)
            {
                // parameter error
                response.StatusCode = 400;
                return BuildHTML("Error...");
            }

            error = handleMouseUp(uri, screen);
            if (error)
            {
                // parameter error
                response.StatusCode = 400;
                return BuildHTML("Error...");
            }

            return BuildHTML("Updating...");
        }
Esempio n. 33
0
 /// <summary>
 /// Get a copy of the requested device screen image from cache
 /// </summary>
 /// <param name="response"></param>
 /// <param name="uri"></param>
 /// <returns></returns>
 public override byte[] HandleRequest(HttpListenerResponse response, String[] uri)
 {
     int requested = GetRequestedScreenDevice(uri, screens);
     lastScreenRequested = requested;
     response.Headers.Set("Content-Type", "image/png");
     return caches[requested];
 }
Esempio n. 34
0
 public ListenerResponse(HttpListenerResponse response, IRequest request = null)
 {
     this.response = response;
     this.Request = request;
     this.Cookies = new Cookies(this);
     this.Items = new Dictionary<string, object>();
 }
Esempio n. 35
0
 public HttpListenerResponse(HttpListenerCommunicationContext context, System.Net.HttpListenerResponse response)
 {
     _context                    = context;
     _nativeResponse             = response;
     Headers                     = new HttpHeaderDictionary();
     Entity                      = new HttpEntity(Headers, _tempStream);
     _nativeResponse.SendChunked = false;
 }
Esempio n. 36
0
 public HttpListenerResponse(HttpListenerCommunicationContext context, System.Net.HttpListenerResponse response)
 {
     _context        = context;
     _nativeResponse = response;
     Headers         = new HttpHeaderDictionary();
     // TODO: Wrap stream and send chunked when needed if write starts before sending response
     Entity = new HttpEntity(Headers, _tempStream);
     _nativeResponse.SendChunked = false;
 }
Esempio n. 37
0
 static void ResponseWrite(string type, string msg, System.Net.HttpListenerResponse response)
 {
     //使用Writer输出http响应代码
     using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.OutputStream, new UTF8Encoding()))
     {
         response.ContentType = type + ";charset=utf-8";
         writer.WriteLine(msg);
         writer.Close();
         response.Close();
     }
 }
Esempio n. 38
0
        static void httpListenerCallback(IAsyncResult result)
        {
            System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;
            try
            {
                if (listener.IsListening)
                {
                    // continue to listen
                    listener.BeginGetContext(new AsyncCallback(httpListenerCallback), listener);

                    // handle the incoming request
                    System.Net.HttpListenerContext context = listener.EndGetContext(result);
                    System.Net.HttpListenerRequest request = context.Request;
                    string responseString;
                    if (string.Compare("/appletv/us/js/application.js", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\application.js");
                    }
                    else if (string.Compare("/appletv/us/nav.xml", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\index.xml");
                    }
                    else if (string.Compare("/appletv/studios/marvel/ironman3/index-hd.xml", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\ironman3.index-hd.xml");
                    }
                    else if (string.Compare("/appletv/studios/marvel/ironman3/videos/trailer1-hd.xml", request.Url.LocalPath, true) == 0)
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\ironman3.videos.trailer1-hd.xml");
                    }
                    else
                    {
                        responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\atv\index.xml");
                    }
                    System.Net.HttpListenerResponse response = context.Response;
                    //string responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\atv\index.xml");
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
Esempio n. 39
0
 /// <summary>
 /// http响应
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="response"></param>
 /// <param name="type"></param>
 public void ResponseWrite(string msg, System.Net.HttpListenerResponse response, string type = "text/plain")
 {
     try
     {
         //使用Writer输出http响应代码
         using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.OutputStream, new UTF8Encoding()))
         {
             response.ContentType = type + ";charset=utf-8";
             writer.WriteLine(msg);
             writer.Close();
             response.Close();
         }
     }
     catch (Exception exception)
     {
     }
 }
Esempio n. 40
0
        // Send HTTP Response
        private void sendHTMLResponse(string request)
        {
            try
            {
                // Get the file content of HTTP Request
                FileStream   fs = new FileStream(request, FileMode.Open, FileAccess.Read, FileShare.None);
                BinaryReader br = new BinaryReader(fs);

                // The content Length of HTTP Request
                byte[] respByte = new byte[(int)fs.Length];
                br.Read(respByte, 0, (int)fs.Length);

                br.Close();
                fs.Close();

                // 以Response屬性取得HTTP伺服端的輸出串流,則HTTP伺服端之回應
                httpResponse = httpContext.Response;

                // HTTP回應資料內容的大小
                httpResponse.ContentLength64 = respByte.Length;

                // HTTP回應資料內容的MIME格式
                httpResponse.ContentType = getContentType(request);

                // 取得伺服端HTTP回應之資料串流
                System.IO.Stream output = httpResponse.OutputStream;

                // 回應HTML網頁內容至用戶端瀏覽器
                output.Write(respByte, 0, respByte.Length);

                output.Close();
                httpResponse.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.StackTrace.ToString());

                if (httpResponse != null)
                {
                    httpResponse.Close();
                }
            }
        }
Esempio n. 41
0
        private void OnResponse(System.Net.HttpListenerResponse response, System.Net.HttpListenerRequest request)
        {
            String reqStrURlRaw = request.Url.ToString();

            if (!LocalResource.LocalFileExist(reqStrURlRaw) && request.UrlReferrer == null)
            {
                reqStrURlRaw = "/";
            }
            else
            {
                reqStrURlRaw = LocalResource.UrlToLocalRef(reqStrURlRaw, request.UrlReferrer.ToString());
            }
            if (!LocalResource.LocalFileExist(reqStrURlRaw))
            {
                reqStrURlRaw = "/";
            }
            bool       bBlockFile = false;
            FileStream fr         = LocalResource.GetFStream(reqStrURlRaw, ref bBlockFile);

            if (null == fr)
            {
                request.InputStream.Close();
                return;
            }

            BinaryWriter bw = CreateBinaryStreamWriter(response.OutputStream);
            StreamWriter sw = CreateStringStreamWriter(response.OutputStream);

            try
            {
                byte[] datas = new byte[4096];
                int    rlen  = 0;
                while ((rlen = fr.Read(datas, 0, datas.Length)) > 0)
                {
                    if (bBlockFile)
                    {
                        bw.Write(datas);
                    }
                    else
                    {
                        Encoding utf8    = Encoding.UTF8;
                        Encoding unicode = Encoding.Unicode;
                        byte[]   dataPtr = datas;
                        if (rlen < 4096)
                        {
                            dataPtr = new byte[rlen];
                            Array.Copy(datas, dataPtr, rlen);
                        }
                        byte[] uniBytes = Encoding.Convert(utf8, unicode, dataPtr);
                        Char[] uniChars = new Char[unicode.GetCharCount(uniBytes, 0, uniBytes.Length)];
                        unicode.GetChars(uniBytes, 0, uniBytes.Length, uniChars, 0);
                        sw.Write(new string(uniChars));
                        dataPtr = null;
                    }
                }

                sw.Flush();
                bw.Flush();
                bw.Close();
                sw.Close();
                datas = null;
            }
            catch { }

            bw = null;
            sw = null;
            fr.Close();
            fr = null;
        }
        /// <summary>
        /// Callback when a HTTP request comes in on the port listener and is handed off
        /// to a thread for processing.  This method
        /// </summary>
        /// <param name="result">IAsyncResult containing the HTTPListener</param>
        public void ListenerCallback(IAsyncResult result)
        {
            HttpListener        listener = (HttpListener)result.AsyncState;
            HttpListenerContext context  = null;

            if (listener == null)
            {
                return;
            }

            try {
                // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework,
                // blocks until there is a request to be processed or some type of data is available.
                context = listener.EndGetContext(result);
            } catch (Exception ex) {
                // You will get an exception when httpListener.Stop() is called
                // because there will be a thread stopped waiting on the .EndGetContext()
                // method, and again, that is just the way most Begin/End asynchronous
                // methods of the .NET Framework work.
                Console.WriteLine("HttpListener Error", ex);
                return;
            } finally {
                // Once we know we have a request (or exception), we signal the other thread
                // so that it calls the BeginGetContext() (or possibly exits if we're not
                // listening any more) method to start handling the next incoming request
                // while we continue to process this request on a different thread.
                listenForNextRequest.Set();
            }

            if (context == null)
            {
                return;
            }

            Console.WriteLine("Start: {0}", DateTime.Now.ToString());


            System.Net.HttpListenerRequest request = context.Request;
            Console.WriteLine("{0}: {1}", PORT, request.RawUrl);

            if (request.HasEntityBody)
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(request.InputStream, request.ContentEncoding)) {
                    string requestData = sr.ReadToEnd();
                }
            }

            // Obtain a response object
            using (System.Net.HttpListenerResponse response = context.Response) {
                /*
                 * cmpa --+
                 *  cmpg 4  000000c8 == 0000000000000001
                 *  cmnm 10 648a861f == devicename
                 *  cmty 4  648a861f == ipod
                 */

                DACPResponse dacpResponse = new PairingClientResponse();
                byte[]       output       = dacpResponse.GetBytes();

                Console.WriteLine(new UTF8Encoding(false).GetString(output));
                response.StatusCode      = (int)HttpStatusCode.OK;
                response.ContentLength64 = output.LongLength;
                response.OutputStream.Write(output, 0, output.Length);
            }

            Console.WriteLine("End: {0}", DateTime.Now.ToString());
        }
Esempio n. 43
0
 public HttpListenerResponse(HttpListenerContext context)
 {
     Response = context.Response;
 }
Esempio n. 44
0
 public SystemHttpResponse(SystemHttpContext context, System.Net.HttpListenerResponse response)
 {
     _context  = context;
     _response = response;
 }
        private void WxHttpServer_OnDataReceived(System.Net.HttpListenerRequest reqeust, System.Net.HttpListenerResponse response)
        {
            String dataString = "";

            if (reqeust.HttpMethod == "POST")
            {
                Console.WriteLine("POST");
                Stream       stream       = reqeust.InputStream;
                BinaryReader binaryReader = new BinaryReader(stream);

                byte[] data = new byte[reqeust.ContentLength64];
                binaryReader.Read(data, 0, (int)reqeust.ContentLength64);

                dataString = Encoding.UTF8.GetString(data);
                lock (locker)
                {
                    foreach (String keyWords in keyWordList)
                    {
                        if (dataString == "")
                        {
                            return;
                        }
                        if (dataString.IndexOf(keyWords) > -1)
                        {
                            DeleteUser(dataString, keyWords);
                            break;
                        }
                    }
                }
            }

            string responseString = "";

            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
Esempio n. 46
0
 public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response)
 {
 }
Esempio n. 47
0
 public ListenerResponse(System.Net.HttpListenerResponse response)
 {
     this.response = response;
     this.Cookies  = new Cookies(this);
     this.Items    = new Dictionary <string, object>();
 }
Esempio n. 48
0
        /// <summary>
        /// Callback when a HTTP request comes in on the port listener and is handed off
        /// to a thread for processing.  This method
        /// </summary>
        /// <param name="result">IAsyncResult containing the HTTPListener</param>
        protected void ListenerCallback(IAsyncResult result)
        {
            try {
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = null;
                if (listener == null)
                {
                    Console.WriteLine("Listener null so returning...");
                    return;
                }

                try {
                    // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework,
                    // blocks until there is a request to be processed or some type of data is available.
                    context = listener.EndGetContext(result);
                } catch (Exception ex) {
                    // You will get an exception when httpListener.Stop() is called
                    // because there will be a thread stopped waiting on the .EndGetContext()
                    // method, and again, that is just the way most Begin/End asynchronous
                    // methods of the .NET Framework work.
                    Console.WriteLine("HttpListener Stopped: {0}", ex.Message);
                    ReleaseAllLatches();
                    return;
                } finally {
                    // Once we know we have a request (or exception), we signal the other thread
                    // so that it calls the BeginGetContext() (or possibly exits if we're not
                    // listening any more) method to start handling the next incoming request
                    // while we continue to process this request on a different thread.
                    listenForNextRequest.Set();
                }

                if (context == null)
                {
                    return;
                }

                Console.WriteLine("HTTP START: {0}", DateTime.Now.ToString());

                System.Net.HttpListenerRequest request = context.Request;
                Console.WriteLine("{0}: {1}", PORT, request.RawUrl);
                if (request.HasEntityBody)
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(request.InputStream, request.ContentEncoding)) {
                        string requestData = sr.ReadToEnd();
                    }
                }

                bool debug_enabled = true;
                if (debug_enabled)
                {
                    Console.WriteLine("    HTTP User-Agent: {0}", request.UserAgent);
                    foreach (String s in request.Headers.AllKeys)
                    {
                        Console.WriteLine("    Header {0,-10} {1}", s, request.Headers[s]);
                    }
                }



                // determine if the client is requesting a compressed response
                string acceptEncoding = request.Headers["Accept-Encoding"];
                bool   isCompressed   = (!string.IsNullOrEmpty(acceptEncoding) && (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate")));
                Console.WriteLine("Accept-Encoding: {0} Compressed: {1}", acceptEncoding, isCompressed);

                // Obtain a response object
                using (System.Net.HttpListenerResponse response = context.Response) {
                    try {
                        response.ContentType = "application/x-dmap-tagged";
                        response.AddHeader("DAAP-Server", this.GetApplicationName() + " " + this.Version);
                        this.DispatchRequest(request, response, isCompressed);
                    } catch (DACPSecurityException ex) {
                        Console.WriteLine("DACP Security Error: " + ex.Message);
                        response.StatusCode = (int)HttpStatusCode.Forbidden;
                        response.OutputStream.WriteByte(0);
                    } catch (Exception ex) {
                        Console.WriteLine("DACP Server Error: " + ex.Message);
                        response.StatusCode = DACPResponse.MSTT_NO_CONTENT;
                        response.OutputStream.WriteByte(0);
                    }
                }
            } catch (Exception httpEx) {
                Console.WriteLine("DACP Server Error: " + httpEx.Message, httpEx);
            }


            Console.WriteLine("HTTP END: {0}", DateTime.Now.ToString());
        }
Esempio n. 49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SystemHttpResponse"/> class.
 /// </summary>
 /// <param name="context">The context.</param>
 public SystemHttpResponse(System.Net.HttpListenerContext context)
 {
     _response = context.Response;
     Cookies   = new SystemCookieCollection(_response.Cookies);
 }
 internal HttpResponseStream(Stream stream, HttpListenerResponse response, bool ignore_errors)
 {
     _response      = response;
     _ignore_errors = ignore_errors;
     _stream        = stream;
 }
 public HttpListenerContext(HttpListenerRequest request, HttpListenerResponse response)
 {
     Request  = request;
     Response = response;
 }
Esempio n. 52
0
        private void WxHttpServer_OnDataReceived(System.Net.HttpListenerRequest reqeust, System.Net.HttpListenerResponse response)
        {
            String dataString     = "";
            string responseString = "";

            if (reqeust.HttpMethod == "POST")
            {
                Console.WriteLine("POST");
                Stream       stream       = reqeust.InputStream;
                BinaryReader binaryReader = new BinaryReader(stream);

                byte[] data = new byte[reqeust.ContentLength64];
                binaryReader.Read(data, 0, (int)reqeust.ContentLength64);
                dataString = Encoding.UTF8.GetString(data);

                JavaScriptSerializer js            = new JavaScriptSerializer();
                ClientCmd            clientCmd     = js.Deserialize <ClientCmd>(dataString);
                StringBuilder        stringBuilder = new StringBuilder();
                stringBuilder.Append(clientCmd.Wxid);
                Boolean result = DeleteWxUser(stringBuilder);

                responseString = (
                    new
                {
                    cmd = clientCmd.Cmd,
                    result = result.ToString()
                }
                    ).ToString();
            }

            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
Esempio n. 53
0
 internal HttpListenerContext(HttpConnection cnc)
 {
     this.cnc = cnc;
     request  = new HttpListenerRequest(this);
     response = new HttpListenerResponse(this);
 }
Esempio n. 54
0
 internal ResponseStream(Stream stream, HttpListenerResponse response, bool ignore_errors)
 {
     this.response      = response;
     this.ignore_errors = ignore_errors;
     this.stream        = stream;
 }
Esempio n. 55
0
 public ListenerResponse(System.Net.HttpListenerResponse response)
 {
     this.response = response;
     this.Cookies  = new Cookies(this);
 }