gpt4 book ai didi

c# - HTTP WCF 服务保持流打开

转载 作者:太空宇宙 更新时间:2023-11-03 10:32:17 24 4
gpt4 key购买 nike

我正在尝试通过 HTTP 将数据流式传输到客户端。为实现这一点,我使用了带有 WebHttpBinding 的 WCF 服务。问题是我的操作返回的 System.IO.Stream 在我可以写入内容之前已关闭。我想让流保持打开状态,直到需要向其中写入数据。通常这不会超过半分钟。

在服务请求方法中,我创建了一个新的 System.IO.MemoryStream 实例,我将其放入所有流的集合中,并将其作为函数输出返回。稍后当有可用的音频数据时,我将写入集合中的所有流。但到那时所有的请求都已关闭。当我转到端点 url 时,浏览器标准播放器完全变灰。我还用 REST 客户端进行了测试,它告诉我请求在 return 语句之后立即关闭。

问题是我们使用 Libspotify SDK 来检索音乐。每个周期发送 8192 字节的 PCM 数据。我们希望让用户能够从 Chromecast 设备播放他们的音乐。 Chromecast 不支持 PCM 数据,这就是我们使用 libmp3lame 将其转换为 MP3,然后通过输出流将其发送到 Chromecast 的原因。为了使这种方法起作用,我们需要连接保持事件状态,即使没有实际数据通过 Stream 发送也是如此。

可以找到Libspotify 音乐传送回调here .

这是我设置服务的方式:

/// <summary>
/// The WCF service host.
/// </summary>
private ServiceHost ServiceHost;

/// <summary>
/// Start the HTTP WCF service.
/// </summary>
public void startListening()
{
if (ServiceHost == null)
{
ServiceHost = new ServiceHost(typeof(StreamingService));

var binding = new WebHttpBinding(WebHttpSecurityMode.None);
binding.TransferMode = TransferMode.StreamedResponse;

var endpoint = ServiceHost.AddServiceEndpoint(typeof(StreamingContract), binding, new Uri(streamAddress));
endpoint.EndpointBehaviors.Add(new WebHttpBehavior());

ServiceHost.Open();
}
}

这是服务实现:

[ServiceContract(Name="StreamingContract")]
interface StreamingContract
{
[WebGet(UriTemplate="audio")]
[OperationContract()]
Stream Audio();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
IncludeExceptionDetailInFaults = true)]
public class StreamingService : StreamingContract
{
public System.IO.Stream Audio()
{
var stream = new System.IO.MemoryStream();
App.Logic.streaming.streams.Add(stream);

WebOperationContext.Current.OutgoingResponse.ContentType = "audio/mp3";
WebOperationContext.Current.OutgoingResponse.ContentLength = 1000;

return stream;
}
}

我还尝试在 ServiceContractAudio() 上设置:[OperationContext(AutoDisposeParameter=false)]。这只是开始抛出 System.InvalidOperationException。我还认为内容长度未知可能是个问题,这也无济于事。

最佳答案

您的服务正在做它应该做的事 - 返回一个空流然后关闭连接。

听起来您想等待该流被异步填充。为此,您必须实现某种回调。你应该看看 Task.Run() method ,因为这将是在 .NET 中实现异步逻辑的标准方式。

关于c# - HTTP WCF 服务保持流打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29550898/

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