gpt4 book ai didi

c# - 从 OperationContract 方法返回图像(WCF 服务)

转载 作者:太空狗 更新时间:2023-10-30 00:15:54 25 4
gpt4 key购买 nike

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

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

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

服务.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 接口(interface):

[ServiceContract]
public interface IScreenShot
{
[OperationContract]
System.Drawing.Image GetScreenShot();
}

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

最佳答案

我想通了。

  • 首先使用 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;
}
}

接口(interface):

[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());
}
}

关于c# - 从 OperationContract 方法返回图像(WCF 服务),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10584260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com