Я пишу клиент WCF, который читает файл прошивки, копирует его в байтовый массив и отправляет на сервер WCF.Сервер мигает на другое устройство, подключенное к нему.И сервер, и клиент написаны мной.
Я создал встроенный сервис WCF в коде без использования раздела конфигурации модели сервиса в файле configuration.xml.Поскольку на перепрошивку серверу может потребоваться минута, я реализовал контракт как асинхронный, поэтому клиенту не нужно ждать завершения перепрошивки.И сервер, и клиент используют один и тот же интерфейс IFirmwareUpgrade.
Однако, когда я запускаю клиент и сервер, я получаю исключение ServiceModel.ActionNotSupportedException.Вот подробности об исключении.
The message with Action 'ServiceContractNS/UpdatorContract/UpgradeFirmware' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher.This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).
Вот код сервера
namespace Updator
{
partial class UpdatorWCFService : IUpdator, IFirmwareUpgrade
{
public bool UpgradeFirmware(string deviceIPAddress, byte[] buffer)
{
m_RFM220Manager.UpgradeFirmware(deviceIPAddress, buffer);
return true;
}
public System.IAsyncResult BeginUpgradeFirmware(string DeviceIPAddress, byte[] buffer, System.AsyncCallback callback, object asyncState)
{
Console.WriteLine("BeginServiceAsyncMethod called with: \"{0}\"", DeviceIPAddress);
//Do something
return new CompletedAsyncResult<bool>(true);
}
public bool EndUpgradeFirmware(System.IAsyncResult r)
{
CompletedAsyncResult<bool> result = r as CompletedAsyncResult<bool>;
Console.WriteLine("EndServiceAsyncMethod called with: \"{0}\"", result.Data);
//return result.Data;
return false;
}
}
// Simple async result implementation.
class CompletedAsyncResult<T> : IAsyncResult
{
T data;
public CompletedAsyncResult(T data)
{ this.data = data; }
public T Data
{ get { return data; } }
#region IAsyncResult Members
public object AsyncState
{ get { return (object)data; } }
public WaitHandle AsyncWaitHandle
{ get { throw new Exception("The method or operation is not implemented."); } }
public bool CompletedSynchronously
{ get { return true; } }
public bool IsCompleted
{ get { return true; } }
#endregion
}
}
Так создается служба
NetTcpBinding binding = new NetTcpBinding();
binding.MaxConnections = (int)m_Configuration.wcftcpchannel.maxconnection;
binding.TransferMode = TransferMode.Buffered;
binding.MaxBufferSize = 20 * 1024 * 1024;
binding.MaxReceivedMessageSize = binding.MaxBufferSize;
binding.ReaderQuotas.MaxArrayLength = 2147483647;
binding.Security.Mode = SecurityMode.None;
binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
binding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.None;
binding.Security.Message.ClientCredentialType = MessageCredentialType.None;
// Step 3 of the hosting procedure: Add a service endpoint.
m_UITCPHost.AddServiceEndpoint(
typeof(IUpdator),
binding,
"UpdatorWCFService");
// Step 5 of the hosting procedure: Start (and then stop) the service.
m_UITCPHost.Open(new TimeSpan(0, 0, 0, m_Configuration.wcftcpchannel.timeoutinms));
Вот договор
[ServiceContract(Name = "UpdatorContract", Namespace = "ServiceContractNS", ConfigurationName = "UpdatorContract")]
public interface IFirmwareUpgrade
{
[OperationContract]
bool UpgradeFirmware(string DeviceIPAddress, byte[] buffer);
//[System.ServiceModel.OperationContractAttribute(AsyncPattern = true, Action = "ServiceContractNS/UpdatorContract/UpgradeFirmware", ReplyAction = "ServiceContractNS/UpdatorContract/UpgradeFirmwareResponse")]
[OperationContract(AsyncPattern=true)]
System.IAsyncResult BeginUpgradeFirmware(string DeviceIPAddress, byte[] buffer, System.AsyncCallback callback, object asyncState);
// Note: There is no OperationContractAttribute for the end method.
bool EndUpgradeFirmware(System.IAsyncResult result);
}
Это раздел конфигурации в клиенте
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="NetTcpBinding_UpdatorContract" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10"
maxBufferPoolSize="20971520" maxBufferSize="20971520" maxConnections="10"
maxReceivedMessageSize="20971520">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="2147483647"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="None">
<transport clientCredentialType="None" protectionLevel="None" />
<message clientCredentialType="None" />
</security>
</binding>
</netTcpBinding>
</bindings>
<client>
<endpoint address="net.tcp://192.158.96.120:8000/Updator/UpdatorWCFService"
binding="netTcpBinding" bindingConfiguration="NetTcpBinding_UpdatorContract"
contract="UpdatorContract" name="NetTcpBinding_UpdatorContract" />
</client>
</system.serviceModel>
Это класс Client для асинхронной реализации
public class FirmwareUpgradeClient : System.ServiceModel.ClientBase<IFirmwareUpgrade>, IFirmwareUpgrade
{
private BeginOperationDelegate onBeginUpgradeFirmwareDelegate;
private EndOperationDelegate onEndUpgradeFirmwareDelegate;
private System.Threading.SendOrPostCallback onUpgradeFirmwareCompletedDelegate;
public event System.EventHandler<UpgradeFirmwareCompletedEventArgs> UpgradeFirmwareCompleted;
public bool UpgradeFirmware(string DeviceIPAddress, byte[] buffer)
{
return base.Channel.UpgradeFirmware(DeviceIPAddress, buffer);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public System.IAsyncResult BeginUpgradeFirmware(string DeviceIPAddress, byte[] buffer, System.AsyncCallback callback, object asyncState)
{
return base.Channel.BeginUpgradeFirmware(DeviceIPAddress, buffer, callback, asyncState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public bool EndUpgradeFirmware(System.IAsyncResult result)
{
return base.Channel.EndUpgradeFirmware(result);
}
private System.IAsyncResult OnBeginUpgradeFirmware(object[] inValues, System.AsyncCallback callback, object asyncState)
{
string DeviceIPAddress = ((string)(inValues[0]));
byte[] buffer = ((byte[])(inValues[1]));
return this.BeginUpgradeFirmware(DeviceIPAddress, buffer, callback, asyncState);
}
private object[] OnEndUpgradeFirmware(System.IAsyncResult result)
{
bool retVal = this.EndUpgradeFirmware(result);
return new object[] {
retVal};
}
private void OnUpgradeFirmwareCompleted(object state)
{
if ((this.UpgradeFirmwareCompleted != null))
{
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.UpgradeFirmwareCompleted(this, new UpgradeFirmwareCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
}
}
public void UpgradeFirmwareAsync(string DeviceIPAddress, byte[] buffer)
{
this.UpgradeFirmwareAsync(DeviceIPAddress, buffer, null);
}
public void UpgradeFirmwareAsync(string DeviceIPAddress, byte[] buffer, object userState)
{
try
{
if ((this.onBeginUpgradeFirmwareDelegate == null))
{
this.onBeginUpgradeFirmwareDelegate = new BeginOperationDelegate(this.OnBeginUpgradeFirmware);
}
if ((this.onEndUpgradeFirmwareDelegate == null))
{
this.onEndUpgradeFirmwareDelegate = new EndOperationDelegate(this.OnEndUpgradeFirmware);
}
if ((this.onUpgradeFirmwareCompletedDelegate == null))
{
this.onUpgradeFirmwareCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnUpgradeFirmwareCompleted);
}
base.InvokeAsync(this.onBeginUpgradeFirmwareDelegate, new object[] {
DeviceIPAddress,
buffer}, this.onEndUpgradeFirmwareDelegate, this.onUpgradeFirmwareCompletedDelegate, userState);
}
catch (Exception e)
{
}
}
}