1

我想在线程中处理http请求,代码如下,问题是OutputStream(如代码中所述)无法写入。当我把这个进程放在主线程中时,没问题。你能给我什么建议吗?

    public partial class MainWindow : Window
    {
       private void Window_Loaded(object sender, RoutedEventArgs e)
       {
            var server = new HttpServer();
            try
            {
                server.EndPoint = new IPEndPoint(127.0.0.0, 80); //set webServer para
                server.Start(); //start webServer
                server.RequestReceived += server_RequestReceived; //register the event
            }
            catch (Exception ex)
            {
                return;
            }
       }
       private void server_RequestReceived(object sender, HttpRequestEventArgs e)
       {
           var dataProcess = new Action<HttpRequestEventArgs>(DataProcess);
           Dispatcher.BeginInvoke(dataProcess,e); //start thread
       }
       private void DataProcess(HttpRequestEventArgs e)
       {
           StreamReader sr = new StreamReader(@"c:\test.txt");
           string text = sr.ReadToEnd();
           using (var writer = new StreamWriter(e.Response.OutputStream)) //**Cannot write stream**
           {
               writer.Write(text);
           }
           sr.Close();
       }
    }
4

2 回答 2

1

我认为您的请求在新线程运行之前已经关闭。您可以做的是在新线程中执行整个请求。就像是:

public partial class MainWindow : Window
{
   private void Window_Loaded(object sender, RoutedEventArgs e)
   {
        var start = new Action<HttpRequestEventArgs>(Start);
        Dispatcher.start(start,e); //start thread
   }

   private void Start(HttpRequestEventArgs e)
   {
        var server = new HttpServer();
        server.EndPoint = new IPEndPoint(127.0.0.0, 80); //set webServer para
        server.Start(); //start webServe
        server.RequestReceived += server_RequestReceived; //register the event
   }

   private void server_RequestReceived(object sender, HttpRequestEventArgs e)
   {
       StreamReader sr = new StreamReader(@"c:\test.txt");
       string text = sr.ReadToEnd();
       using (var writer = new StreamWriter(e.Response.OutputStream)) //**Cannot write stream**
       {
           writer.Write(text);
       }
       sr.Close();
   }
}
于 2012-05-15T04:28:02.383 回答
0

大多数e.Response.OutputStream可能是只写流,其中包含从服务器接收到的响应。

根据您想要做什么,您可以写入请求流或从 OutputStream 读取。

注意:您正在使用一些自定义类,因此建议完全基于方法名称。

于 2012-05-15T04:36:23.753 回答