如何在一个线程中写另一个线程中的stream?

datacloud 2012-05-26 10:06:39
问题是这样的:
服务器端接受客户端的http请求,每来一个请求(一个事件)就会创建一个新的子窗口(一个新线程)进行人工交互。
请求是封装好的类,其中有一个类型为stream的response域,用来返回应答给客户端。
我现在想在子窗口中输入应答内容,回车后将该内容写到response域中,但不知如何实现这个功能。
下面两种方案都未能实现:
1、尝试着在创建新的子窗口时将http请求一并传入,然后在子窗口中直接写response域,但总是报告“流不可写”。
2、尝试在子窗口中回车后,将应答内容传给主窗口,但在主窗口因为会处理很多请求,那么这个内容该传给谁呢?

盼高人给些建议。
...全文
72 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
datacloud 2012-05-26
  • 打赏
  • 举报
回复
是这样的。代码如下。

public partial class MainWindow : Window
{
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//startup web server
Dispatcher.BeginInvoke(new Action(Start));
}

private void Start()
{
var server = new HttpServer();
try
{
server.EndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
server.RequestReceived += DataProcess;
}
catch (Exception ex)
{
return;
}
}

private void DataProcess(object sender, HttpRequestEventArgs e)
{
//create a new window in which user can input the response for the http request e.
var pw = (PrivateWindow)Dispatcher.Invoke(new Func<HttpRequestEventArgs, PrivateWindow>(CreatePrivateWindow), e);
}

public PrivateWindow CreatePrivateWindow(string windowKey, HttpRequestEventArgs e)
{
var pw = new PrivateWindow();
pw.httpRequest = e;//pass the stream to thread here.
windows.Add(pw);
return pw;
}
}

public partial class PrivateWindow : Window
{
private void btnSendMessage_Click(object sender, RoutedEventArgs e)
{
string messageText = new TextRange(txtWriteMessage.Document.ContentStart, txtWriteMessage.Document.ContentEnd).Text.Trim();
//write the response in thread
Dispatcher.BeginInvoke(new Action<HttpRequestEventArgs, string>(WriteToStream), httpRequest, messageText);
}
private void WriteToStream(HttpRequestEventArgs e, string str)
{
//**here occurs "stream can not be written" error.**
using (var writer = new StreamWriter(e.Response.OutputStream))
{
writer.Write(str);
}
}
}
机器人 2012-05-26
  • 打赏
  • 举报
回复
你代码怎么写的呢?

在你应用里,创建一个静态单例的Server,然后在事件里新开窗体处理就可以了吧。
datacloud 2012-05-26
  • 打赏
  • 举报
回复
使用了现成的一个:http://github.com/pvginkel/NHttp
机器人 2012-05-26
  • 打赏
  • 举报
回复
能否先描述下这个服务端是怎么实现的? 是一个HttpListener么?

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧