我正在尝试从WCF服务中获取一个Image。
我有一个OperationContract函数,它向客户机返回一个Image,但是当我从客户机调用它时,我得到了这个异常:
套接字连接被中止。这可能是由于处理邮件时出错、远程主机超过接收超时或基础网络资源问题造成的。本地套接字超时时间是'00:00:59.9619978‘。
客户端:
private void btnNew_Click(object sender, EventArgs e)
{
picBox.Picture = client.GetScreenShot();
}Service.cs:
public Image GetScreenShot()
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bmp = new Bitmap(bounds.Width,bounds.Height))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return Image.FromStream(ms);
}
}
}IScreenShot接口:
[ServiceContract]
public interface IScreenShot
{
[OperationContract]
System.Drawing.Image GetScreenShot();
}那么为什么会发生这种情况,我该如何解决呢?
发布于 2012-05-15 20:50:24
我已经想明白了。
TransferMode.Streamed或StreamedResponse (取决于您的需要)。Stream.Postion = 0,所以从一开始就开始读取流。在服务中:
public Stream GetStream()
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bmp = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Position = 0; // This is very important
return ms;
}
}接口:
[ServiceContract]
public interface IScreenShot
{
[OperationContract]
Stream GetStream();
}在客户端:
public partial class ScreenImage: Form
{
ScreenShotClient client;
public ScreenImage(string baseAddress)
{
InitializeComponent();
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
binding.TransferMode = TransferMode.StreamedResponse;
binding.MaxReceivedMessageSize = 1024 * 1024 * 2;
client = new ScreenShotClient(binding, new EndpointAddress(baseAddress));
}
private void btnNew_Click(object sender, EventArgs e)
{
picBox.Image = Image.FromStream(client.GetStream());
}
}发布于 2012-05-14 13:45:25
您可以使用Stream返回大型数据/图像。
来自MSDN的示例示例(以流形式返回图像)
发布于 2012-05-14 13:39:33
您需要定义可序列化的东西。默认情况下,System.Drawing.Image是,但不是在WCF上下文中(使用DataContractSerializer)。这可能包括将原始字节作为数组返回,或者序列化到字符串(base64,JSON),或者实现可序列化的DataContract,并且可以随身携带数据。
正如其他人所说,WCF支持流,但这不是问题的症结所在。根据数据的大小,您可能希望这样做,这样做将减少问题本身,因为您将是流字节(从一个明显的,顶层视图)。
您还可以使用看看这个答案来帮助您获取实际的异常细节,比如完整的堆栈跟踪,而不仅仅是故障信息。
https://stackoverflow.com/questions/10584260
复制相似问题