我正在尝试制作一个简单的HTTP侦听器来处理多个请求和响应。 下面的代码描述了到目前为止的工作方式。我不确定我的方法是否正确。我可以处理多个连接还是需要使用异步代码? 我应该在每个新请求中打开一个新线程,然后在响应后将其关闭吗?
private void Form1_Load(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(MyThreadMethod));
listener = new HttpListener();
listener.Prefixes.Add("http://192.168.0.214:8282/");
listener.Prefixes.Add("http://localhost:8282/");
listener.Prefixes.Add("http://127.0.0.1:8282/");
listener.Start();
t.Start();
}
void MyThreadMethod()
{
try
{
for (;;)
{
HttpListenerContext context = listener.GetContext();
string methodName = Convert.ToString(context.Request.Url);//.Replace("/", "")
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = Convert.ToString(Response);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes("Server Answer");
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
}
}
catch(Exception ex)
{
}
}