Example #1
0
        public async void TestHandleClient(TcpClient tcpClient,
                                           CancellationToken token)
        {
            HttpChannel channel = ServerInfo._httpChannels.Add(tcpClient);

            try
            {
                List <byte> cache        = new List <byte>();
                string      ip           = "";
                Stream      inputStream  = tcpClient.GetStream();
                Stream      outputStream = tcpClient.GetStream();

                try
                {
                    ip = GetClientIP(tcpClient);
                    channel.Touch();

                    int  i       = 0;
                    bool running = true;
                    while (running)
                    {
                        HttpRequest request = await HttpProcessor.GetIncomingRequest(inputStream,
                                                                                     cache,
                                                                                     (headers) =>
                        {
#if NO
                            StringBuilder text = new StringBuilder();
                            text.Append(string.Join("\r\n", headers.Select(x => string.Format("{0}: {1}", x.Key, x.Value))));
                            Console.WriteLine("=== headers ===\r\n" + text.ToString());
#endif

                            if (headers.ContainsKey("User-Agent") == false)
                            {
                                return(false);
                            }
                            if (headers["User-Agent"] != "dp2LibraryClient")
                            {
                                throw new InvalidRequestException("请求不是来自 dp2LibraryClient");
                            }
                            return(true);
                        },
                                                                                     token);

                        if (request == null)
                        {
                            Console.WriteLine("client close on request " + i);
                            break;
                        }
                        Console.WriteLine("request " + i);

                        TimeSpan timeout = GetTimeout(request);
                        if (timeout != TimeSpan.MinValue)
                        {
                            channel.Touch(timeout);
                        }
                        else
                        {
                            channel.Touch();
                        }

                        // 添加头字段 _dp2router_clientip
                        request.Headers.Add("_dp2router_clientip", ip);

                        // Console.WriteLine("=== request ===\r\n" + request.Dump());
                        // ServerInfo.WriteErrorLog("=== request ===\r\n" + request.Dump());

                        HttpResponse response = await ServerInfo.WebCall(request, "content", timeout);   // content text.utf-7

                        channel.Touch();
                        // string content = response.GetContentString();

                        // Console.WriteLine("=== response ===\r\n" + response.Dump());

                        await HttpProcessor.WriteResponseAsync(outputStream, response, token);

                        channel.Touch();

                        // Console.WriteLine("http version = '"+request.Version+"'");

                        if (request.Headers.ContainsKey("Connection"))
                        {
                            string strValue = request.Headers["Connection"];
                            if (strValue == "Keep-Alive")
                            {
                                running = true;
                            }
                            else
                            {
                                running = false;
                            }
                        }
                        else
                        {
                            if (StringUtil.CompareVersion(request.Version, "1.1") >= 0)
                            {
                                running = true; // HTTP 1.1 默认就是 Connection Keep-Alive。即便没有 Connection 头字段,也是 Keep-Alive 状态
                            }
                            else
                            {
                                running = false;
                            }
                        }

                        i++;
                    }
                }
                catch (InvalidRequestException ex)
                {
                    // 2016/11/20
                    ServerInfo.WriteErrorLog("ip:" + ip + " : " + ex.Message);
                }
                catch (Exception ex)
                {
                    // 2016/11/14
                    ServerInfo.WriteErrorLog("ip:" + ip + " TestHandleClient() 异常: " + ExceptionUtil.GetExceptionText(ex));
                }
                finally
                {
                    outputStream.Flush();
                    outputStream.Close();
                    outputStream = null;

                    inputStream.Close();
                    inputStream = null;
                }
            }
            finally
            {
                ServerInfo._httpChannels.Remove(channel);
            }
        }