コード例 #1
0
        public void Act()
        {
            byte[] headerBuffer = new byte[8192];
            int    msgLength    = CurrentSocket.Receive(headerBuffer, 0, 8192, SocketFlags.None);

            if (msgLength <= 0)
            {
                return;
            }
            var headerStr = Encoding.UTF8.GetString(headerBuffer);
            Dictionary <string, string> header;
            Dictionary <string, string> @params;

            DecodeHeader(headerStr, out header, out @params);
            long   restPartSize  = long.MaxValue;
            string contentLength = header.ContainsKey("content-length") ? header["content-length"] : string.Empty;

            if (!string.IsNullOrEmpty(contentLength))
            {
                long.TryParse(contentLength, out restPartSize);
            }
            int  sepIndex;
            bool sepfound = FindSepLineIndex(headerBuffer, msgLength, out sepIndex);

            sepIndex++;
            byte[] formBuffer;
            formBuffer = GetFormBuffer(headerBuffer, msgLength, restPartSize, sepIndex, sepfound);
            Dictionary <string, string> files = new Dictionary <string, string>();
            var method = header["method"];

            if (method.Equals("POST", StringComparison.CurrentCultureIgnoreCase))
            {
                string contentTypeInfo = header["content-type"];
                var    contentTypes    = contentTypeInfo.Split(';', StringSplitOptions.RemoveEmptyEntries);
                var    contentType     = contentTypes.Length > 0 ? contentTypes[0] : string.Empty;
                // application/json
                if (contentType.Equals("application/json", StringComparison.CurrentCultureIgnoreCase))
                {
                    var formContent = Encoding.UTF8.GetString(formBuffer);
                    @params.Add("@json", formContent);
                }
                // application/x-www-form-urlencoded
                else if (contentType.Equals("application/x-www-form-urlencoded", StringComparison.CurrentCultureIgnoreCase))
                {
                    string dataLine    = string.Empty;
                    var    formContent = Encoding.UTF8.GetString(formBuffer);
                    int    endingIndex = formContent.IndexOf("\r\n");
                    dataLine = formContent.Substring(0, endingIndex);
                    dataLine = DecodeEscape(dataLine);
                    DecodeParams(dataLine, ref @params);
                }
                else
                {
                    ResponseError(new Exception("Server don't support the data format of POST request yet."));
                    return;
                }
            }
            var container = WebContainer.Create();

            using (var res = container.Serve(new Context(header, @params, files)))
            {
                SendResponse(res.Status, res.MimeType, res.Header, res.Data);
            }
        }