我有这样的代码
public async void Start()
{
Logger.Log(Logger.LogLevel.General, "Beginning Listen!");
HttpListener listener = new HttpListener();
listener.Prefixes.Add(Statics.Config.IniReadValue("http-server"));
listener.Start();
while (true)
{
HttpListenerContext client = await listener.GetContextAsync();
AcceptClient(client);
}
}
public async void AcceptClient(HttpListenerContext client)
{
try
{
string sRequest = Helpers.GetRequestBody(client.Request);
if (sRequest == "")
return;
client.Response.ContentType = "application/json";
//Do a bunch of stuff here
string s = JsonConvert.SerializeObject(response);
byte[] byteArray = Encoding.UTF8.GetBytes(s);
client.Response.ContentLength64 = byteArray.Length;
client.Response.OutputStream.Write(byteArray, 0, byteArray.Length);
client.Response.OutputStream.Close();
client.Response.Close();
}
catch (Exception e)
{
Logger.Log(Logger.LogLevel.Error, e.ToString());
}
}
该代码在使用 .Net 的 Windows 上运行良好,但在我对 Ubuntu 13.04 的测试中,客户端被删除了。我正在使用 Mono 3.2.1。
该代码用于从 C++ 客户端连接的 RPC 服务器,我无法更改。客户端希望连接在整个期间保持打开状态,并且在将此服务器与 Mono 一起使用时在 unix 上出现管道损坏和在 Windows 上出现错误代码 5、eof 时失败。
连接没有问题,但在第一个命令后客户端失败。没有异常(exception)。感谢您的帮助!
编辑 1:我拆开单声道 HttpListener 并直接在我的项目中使用它,现在它在 .Net 上也失败了。代码肯定有问题。附言这次是最新的提交代码。
最佳答案
我的第一个问题,我自己解决了 :D
我做错的是我自己处理了 Request.InputStream 流,这是不应该做的。虽然 .Net 对我这样做没有任何问题,但 Mono 决定检查连接是否可以重用,但在处理流时失败。
所以删除了处理流的函数并且它起作用了!
关于c# - C# Mono 中 HttpListener 中的连接丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23720440/