internal HttpTcpConnection GetConnection(string host, int port, bool ssl) { var key = new HostAndPort() { Host = host, Port = port, Ssl = ssl }; lock (this) { if (!connections.ContainsKey(key)) { connections.Add(key, new Queue <HttpTcpConnection>()); } } var queue = connections[key]; lock (queue) { if (queue.Any()) { var readCount = 0; while (readCount < queue.Count) { readCount++; var conn = queue.Dequeue(); if (!conn.Using && conn.Connected) { queue.Enqueue(conn); conn.Using = true; return(conn); } if (conn.Using || conn.Connected) { queue.Enqueue(conn); } } } var newConn = new HttpTcpConnection() { Using = true }; queue.Enqueue(newConn); return(newConn); } }
public async Task SendRequestAsync(HttpRequest httpRequest) { var isSsl = httpRequest.Uri.Scheme == "https"; this.httpTcpConnection = httpConnectionPool.GetConnection(httpRequest.Uri.Host, httpRequest.Uri.Port, isSsl); if (!httpTcpConnection.Connected) { await httpTcpConnection.ConnectAsync(httpRequest.Uri.Host, httpRequest.Uri.Port); if (isSsl) { SslStream sslStream = new SslStream(httpTcpConnection.NetworkStream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); httpTcpConnection.NetworkStream = sslStream; await sslStream.AuthenticateAsClientAsync(httpRequest.Uri.Host); } } if (httpRequest.Body != null && !httpRequest.Headers.ContainsKey("Content-Type")) { httpRequest.Headers["Content-Type"] = httpRequest.Body.ContentType; } if (httpRequest.Body != null && !httpRequest.Headers.ContainsKey("Content-Length")) { httpRequest.Headers["Content-Length"] = httpRequest.Body.ContentLength.ToString(); } var cmd = httpRequest.ToHttpCommand(); var data = Encoding.UTF8.GetBytes(cmd); var reqStream = new MemoryStream(data); await httpTcpConnection.SendDataAsync(reqStream); if (httpRequest.Body != null) { httpRequest.Body?.WriteBody(httpTcpConnection.NetworkStream); } }