我在将XML发送到端口443上的HTTPS侦听器时收到以下错误。侦听器(C#控制台应用程序)只响应客户端发送的相同XML(一个简单的win表单应用程序) )。如果我将侦听器应用程序更改为HTTP而不是HTTPS,则应用程序可以正常通信。理想情况下,此应用程序将在网络上运行。我已尝试在另一台服务器上托管侦听器应用程序,因此客户端必须访问网络并在与客户端相同的计算机上加载侦听器。我试图消除任何编码问题,因此我可以将其交给我们的网络人员,但我觉得他们需要指明方向。
内部异常:{"无法从传输连接读取数据:远程主机强行关闭现有连接。"}
以下是客户的代码:
xmlOutBox.Text = "";
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
ServicePointManager.MaxServicePointIdleTime = 1;
System.Net.WebRequest req = null;
System.Net.WebResponse rsp = null;
try
{
string uri = urlBox.Text;
req = System.Net.HttpWebRequest.Create(uri);
((HttpWebRequest)req).KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml";
System.IO.StreamWriter writer =
new System.IO.StreamWriter(req.GetRequestStream());
writer.WriteLine(xmlInBox.Text);
writer.Close();
using (var response = (HttpWebResponse)req.GetResponse())
{
var respon = response.GetResponseStream();
using (var reader = new System.IO.StreamReader(respon, Encoding.UTF8))
{
string responseText = reader.ReadToEnd();
xmlOutBox.Text = responseText;
}
}
}
以下是侦听器代码:
static void Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("https://*:443/");
listener.Start();
Console.WriteLine("Listening...");
for(;;)
{
HttpListenerContext ctx = listener.GetContext();
new Thread(new Worker(ctx).ProcessRequest).Start();
}
}
class Worker
{
private HttpListenerContext context;
public Worker(HttpListenerContext context)
{
this.context = context;
}
public void ProcessRequest()
{
string text;
using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
{
text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
我已尝试过此处提到的解决方案:C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send
我还更改了MaxServicePointIdleTime和KeepAlive设置。
答案 0 :(得分:0)
代码方面,OP中显示的内容没有任何问题。问题是使用没有签名证书的HTTPS。在我创建自签名证书并将其绑定到我正在使用的端口(端口443)后,应用程序很乐意接受HTTPS请求。
此处的建议将说明如何逐步纠正问题:
https://stackoverflow.com/questions/11403333/httplistener-with-https-support#=