4

我正在尝试Image从 WCF 服务中获取。

我有一个OperationContract返回给客户端的函数Image,但是当我从客户端调用它时,我得到了这个异常:

套接字连接被中止。这可能是由于处理您的消息时出错或远程主机超出接收超时,或者是潜在的网络资源问题造成的。本地套接字超时为“00:00:59.9619978”。

客户:

private void btnNew_Click(object sender, EventArgs e)
{
    picBox.Picture = client.GetScreenShot();
}

服务.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();
}

那么为什么会发生这种情况,我该如何解决呢?

4

3 回答 3

7

我已经想通了。

  • 首次使用TransferMode.StreamedStreamedResponse(取决于您的需要)。
  • 返回流,不要忘记设置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-15T20:50:24.787 回答
3

您可以使用 Stream 返回大数据/图像。

来自 MSDN 的示例示例(将图像作为流返回)

于 2012-05-14T13:45:25.523 回答
1

您将需要定义可序列化的内容。System.Drawing.Image是,但默认情况下不在 WCF 的上下文中(使用DataContractSerializer)。这可能包括将原始字节作为数组返回,或序列化为字符串(base64,JSON)或实现DataContract可序列化并可以携带数据的 a。

正如其他人所说,WCF 支持流式传输,但这不是问题的症结所在。根据您可能希望执行此操作的数据大小,这样做会减少问题本身,因为您将流式传输字节(从明显的顶级视图)。

您还可以查看此答案以帮助您了解实际的异常详细信息,例如完整的堆栈跟踪,而不仅仅是故障信息。

于 2012-05-14T13:39:33.697 回答