我试图从WCF服务获取图像
我有一个OperationContract函数,它将Image返回给客户端,但是当我从客户端调用它时
我得到了这个例外:The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '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();
}
那为什么会发生这种情况,我该如何解决?
答案 0 :(得分:7)
我已经明白了。
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's a 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());
}
}
答案 1 :(得分:3)
您可以使用Stream返回大数据/图像。
答案 2 :(得分:1)
您需要定义可序列化的内容。 System.Drawing.Image
是,但默认情况下不在WCF的cotnext中(使用DataContractSerializer)。这可能包括将原始字节作为数组返回,或将序列化返回到字符串(base64,JSON)或实现可序列化的DataContract并且可以随身携带数据。
正如其他人所说,WCF支持流媒体,但这不是问题的症结所在。根据您可能希望执行此操作的数据大小,这样做会减少问题,因为您将流式传输字节(从明显的顶级视图)。
您还可以take a look at this answer帮助您获取实际的异常详细信息,例如完整的堆栈跟踪,而不仅仅是故障信息。