我有一个问题:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond URL.
我也遇到这样的问题:
System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host
和
System.Net.WebException: The operation has timed out at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)
我知道以前有人问过这个问题,但请相信我,我最后尝试了几乎每一个解决方案。
奇怪的是这个问题根本没有出现在我这边,只有当客户端尝试使用不是常量的时候才会出现。有时我的应用程序在他们端也能正常工作。
我想要完成的是我创建了一个桌面应用程序(Win Forms 和 C#)并尝试登录客户端,同时向托管在 GODaddy 上的我的 php api 服务器发送请求。
var request = (HttpWebRequest)WebRequest.Create("url");
if (request != null)
{
#region System.Net.WebException
request.Method = "POST";
if (!string.IsNullOrEmpty(body))
{
var requestBody = Encoding.UTF8.GetBytes(body);
request.ContentLength = requestBody.Length;
request.ContentType = "application/json";
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(requestBody, 0, requestBody.Length);
}
}
else
{
request.ContentLength = 0;
}
request.Timeout = 15000;
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
string output = string.Empty;
try
{
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(1252)))
{
if (response.StatusCode == HttpStatusCode.OK)
{
while (!stream.EndOfStream)
{
output += stream.ReadLine();
}
output = stream.ReadToEnd();
}
}
}
}
catch
{
// Excaption Caught here
}
}
请帮帮我。
提前致谢。
最佳答案
尝试添加这个...
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ServicePoint.ConnectionLimit = 12;
MSDN 文章建议每个 CPU 12 个连接,因此限制为 12 个,因为它由 GoDaddy 托管,所以我确信服务器资源是有限的。
关于c# - 连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30092375/