我在WCF方面经验很少,我想通过WCF服务(使用流媒体)从客户端计算机上传服务器上的文件。我读了几个主题并自己写了一个简单的例子,但不幸的是它不起作用
这是一个接口代码:
[ServiceContract]
public interface IService1
{
[OperationContract]
string UpStream(FileStream inStream);
}
这是实施:
public string UpStream(FileStream inStream)
{
using(StreamReader sr = new StreamReader(inStream))
{
var recievedText = sr.ReadToEnd();
if (recievedText != "")
{
return recievedText;
}
else
{
return "nothing";
}
}
}
这是客户端代码:
private void button3_Click(object sender, EventArgs e)
{
service2.Service1Client sc = new service2.Service1Client();
OpenFileDialog opf = new OpenFileDialog();
opf.ShowDialog();
if (opf.FileName != "")
{
using (FileStream inStream = File.Open(opf.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
MessageBox.Show(sc.UpStream(inStream));
}
}
}
我认为问题必须在配置文件或Stream中。当我启动客户端程序并调用UpStream方法时,WCF服务正在接收空流
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services />
<bindings>
<basicHttpBinding>
<binding name="NewBinding0" maxBufferPoolSize="52428800" maxBufferSize="65536000"
maxReceivedMessageSize="6553600000" transferMode="Streamed"
useDefaultWebProxy="true" />
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
如果有人能帮我解决问题,我将非常感激
答案 0 :(得分:1)
流媒体非常有用,但有点难以理解
此MSDN文章提供了大量详细信息https://msdn.microsoft.com/en-us/library/ms733742%28v=vs.110%29.aspx
但是没有让一些细节变得非常清楚
首先,您需要传递消息而不是参数
这看起来像
[MessageContract]
public class DataTransfer
{
[MessageHeader(MustUnderstand = true)]
public DataContract.HandShake Handshake { get; set; }
[MessageBodyMember(Order = 1)]
public Stream Data { get; set; }
//notice that it is using the default stream not a file stream, this is because the filestream you pass in has to be changed to a network stream to be sent via WCF
}
其中HandShake类提供您需要包含的参数以及流
public SaveResponse SaveData(DataTransfer request)
{
using (var stream = new System.IO.MemoryStream())
{
request.Data.CopyTo(stream);
stream.Position = 0;
//this is because you have less control of a stream over a network than one held locally, so by copying from the network to a local stream you then have more control
接下来是配置:您必须在服务器和客户端
上配置流式传输需要这样的东西
<bindings>
<basicHttpBinding>
<binding name="ServiceBinding" transferMode="Streamed" messageEncoding="Mtom" maxReceivedMessageSize="67108864" maxBufferSize="65536" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00">
</binding>
</basicHttpBinding>
</bindings>