我在本地计算机上创建一个简单的HTTP客户端/服务器应用程序,但我不知道为什么在服务器上触发ListenerCallback;但是,在客户端抛出“Web异常:无法连接到删除服务器”时,EndGetContext没有完成。有什么想法吗?这里是代码
class Server
{
static void Main(string[] args)
{
NonblockingListener(new string[] {"http://192.168.0.55:5432/"});
}
public static void NonblockingListener(string[] prefixes)
{
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
Console.WriteLine("Waiting for request to be processed asyncronously.");
result.AsyncWaitHandle.WaitOne();
Console.WriteLine("Request processed asyncronously.");
listener.Close();
}
public static void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener)result.AsyncState;
// Call EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
Stream reader = request.InputStream;
HttpListenerResponse response = context.Response;
string responseString = "<HTML><BODY> Hello World!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
}
class Client
{
public static void Main()
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.0.55:5432");
request.UserAgent = "linkToShare - HTTPWebRequest";
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "data data data data.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
}
}
答案 0 :(得分:0)
您的代码的问题在于,您在服务器中调用EndGetContext
方法,该方法将设置WaitHandle并在任何时间发送响应之前立即关闭服务器。
以下是对代码的轻微修改。
服务器:
class Program
{
private static ManualResetEvent _waitHandle = new ManualResetEvent(false);
static void Main()
{
NonblockingListener(new string[] { "http://+:5432/" });
}
public static void NonblockingListener(string[] prefixes)
{
using (var listener = new HttpListener())
{
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
var result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
Console.WriteLine("Waiting for request to be processed asyncronously.");
// Block here until the handle is Set in the callback
_waitHandle.WaitOne();
Console.WriteLine("Request processed asyncronously.");
listener.Close();
}
}
public static void ListenerCallback(IAsyncResult result)
{
var listener = (HttpListener)result.AsyncState;
var context = listener.EndGetContext(result);
var response = context.Response;
string responseString = "<HTML><BODY>Hello World!</BODY></HTML>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
// Finished sending the response, now set the wait handle
_waitHandle.Set();
}
}
客户端:
class Program
{
static void Main(string[] args)
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.UserAgent] = "linkToShare - HTTPWebRequest";
var valuesToPost = new NameValueCollection
{
{ "param1", "value1" },
{ "param2", "value2" },
};
var result = client.UploadValues("http://127.0.0.1:5432", valuesToPost);
Console.WriteLine(Encoding.UTF8.GetString(result));
}
}
}