I have faced a very strange error in my WCF service, which appears to somehow create a deadlock or thread starvation in socket level when I use NetTcpBinding. I have a quite simple self-hosted service:
class Program
{
static void Main(string[] args)
{
using (ServiceHost serviceHost = new ServiceHost(typeof(TestService)))
{
serviceHost.Open();
Console.WriteLine("Press <ENTER> to terminate service.");
Console.ReadLine();
serviceHost.Close();
}
Uri baseAddress = new Uri("net.tcp://localhost:8014/TestService.svc");
}
}
[ServiceContract]
public interface ITestService
{
[OperationContract]
string GetData(string data);
}
public class TestService: ITestService
{
public string GetData(string data)
{
Console.WriteLine(data);
Thread.Sleep(5000);
return "Ok";
}
}
The configuration part:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBinding" closeTimeout="00:02:00" openTimeout="00:02:00"
receiveTimeout="00:02:00" sendTimeout="00:02:00" maxBufferSize="2000000000"
maxReceivedMessageSize="2000000000" />
</basicHttpBinding>
<netTcpBinding>
<binding name="netTcpBinding" closeTimeout="00:02:00" openTimeout="00:02:00"
receiveTimeout="00:02:00" sendTimeout="00:02:00" listenBacklog="2000"
maxBufferSize="2000000000" maxConnections="1000" maxReceivedMessageSize="2000000000">
<security mode="None">
<transport protectionLevel="EncryptAndSign" />
</security>
</binding>
<binding name="TestServiceTcpEndPoint">
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="CommonServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceThrottling maxConcurrentCalls="1000" maxConcurrentSessions="1000" maxConcurrentInstances="1000" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="ServiceLauncher.TestService" behaviorConfiguration="CommonServiceBehavior">
<endpoint address="" binding="netTcpBinding" bindingConfiguration="netTcpBinding" name="TestServiceTcpEndPoint" contract="ServiceLauncher.ITestService" />
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBinding" name="TestServiceTcpEndPoint" contract="ServiceLauncher.ITestService" />
<endpoint address="mex" binding="mexHttpBinding" bindingName="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8014/TestService.svc"/>
<add baseAddress="http://localhost:1234/TestService.svc"/>
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
And I have a client which consumes this service in many threads with creating new instance for every thread (it is a requirement):
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
{
Thread tr = new Thread(() =>
{
using (var service = new Test.TestServiceClient())
{
var result = service.GetData(i.ToString());
Console.WriteLine(string.Format("{0}: {1} {2}",
DateTime.Now,
result,
Thread.CurrentThread.ManagedThreadId));
}
});
tr.Start();
}
Console.ReadLine();
}
In this case after some requests client raises EndpointNotFoundException, TCP error code 10061, No connection could be made because the target machine actively refused it. The number of requests is different all the time, and it is not the server part because it still works in normal state. And I see it keeps recieving the requests, what is most strangest in this situation. What is also strange that it can make your client host "immortal" after the exception - so that you can't kill it by any mean, except of the reboot of the system. I'm pretty sure that the problem is in low socket level of the client, and it is somehow connected with such a large number of threads, but I didn't succeed in finding something which could explaine the problem.
Every time I've seen the error "No connection could be made because the target machine actively refused it." the problem has not been with the service. Its usually a problem reaching the service.
A couple suggestions:
Avoid using with WCF Proxies. You can pick from several reasonable work arounds.
Read my answer to WCF performance, latency and scalability. Other than starting threads the old fashioned way, its basically the same test app. The post describes all the client causes (I could find) that cause “No connection could be made because the target machine actively refused it” and offers different WCF, TCP, and thread pool settings that can be adjusted.
You could be hitting the internal limits on concurrent TCP/IP connections in windows. Have a look at this article and see if it helps:
http://smallvoid.com/article/winnt-tcpip-max-limit.html
Related
I have a self-hosted C# WCF .Net 4.6.1 Windows service that communicates with another self-hosted WCF service. This works fine when both services are on the same server. However, when I move the server to another computer, I get this error:
System.ServiceModel.CommunicationException: 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. There are no firewalls running on either computer and I get a response when using http://192.168.1.129:6253/eTutorWcfService (using net.tcp in app).
Client app.config:
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IeTutorMessage" />
</basicHttpBinding>
<netTcpBinding>
<binding name="NetTcpBinding_IeTutorMessage" />
</netTcpBinding>
</bindings>
<client>
<endpoint name="BasicHttpBinding_IeTutorMessage"
address="http://localhost:6253/eTutorWcfService"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IeTutorMessage"
contract="eTutorServiceReference.IeTutorMessage" />
<endpoint name="NetTcpBinding_IeTutorMessage"
address="net.tcp://localhost:6254/eTutorWcfService"
binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_IeTutorMessage"
contract="eTutorServiceReference.IeTutorMessage" >
<identity>
<servicePrincipalName value = ""/>
</identity>
</endpoint>
</client>
Server app.config:
<services>
<service name="eTutorServer.eTutorWcfService"
behaviorConfiguration="myeTutorServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:6253/eTutorWcfService"/>
<add baseAddress="net.tcp://localhost:6254/eTutorWcfService"/>
</baseAddresses>
</host>
<endpoint
address="http://localhost:6253/eTutorWcfService"
binding="basicHttpBinding"
contract="eTutorServer.IeTutorMessage" />
<endpoint
address="net.tcp://localhost:6254/eTutorWcfService"
binding="netTcpBinding"
contract="eTutorServer.IeTutorMessage" />
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
<endpoint
address="mex"
binding="mexTcpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="myeTutorServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
The client code:
EndpointAddress address = new EndpointAddress("net.tcp://" + eTutorServiceIp + ":6254/eTutorWcfService");
eTutorServiceReference.IeTutorMessageClient client = new eTutorServiceReference.IeTutorMessageClient("NetTcpBinding_IeTutorMessage", address);
try
{
rtn = client.eTutorMessage(itm);
client.Close();
}
When the client tries to connect, the output window of the server shows an SecurityTokenValidationException but I'm not sure what to do about that or if it means something relevant. I'm sure this has something to do with security but I don't know what to add where.
First, Nettcpbinding use transport security mode and authenticate the client with windows credential by default.
WCF throws exception that the server has rejected the client credentials, what is the default security mode for NetTCP in WCF
Then, when we change the server configuration and re-host the service, we should re-generate the client proxy class when we calling it. besides, we may need to change the endpoint address in the client configuration since Localhost is generated by default.
I can live with this but would really like to know how to do it
without security.
At last, when we change the security to None, the client does not need to provide the credentials to invoke the service. I suggest you re-host the service and re-generate the client proxy class. I have made a demo, wish it is useful to you.
Server end(console application)
class Program
{
static void Main(string[] args)
{
using (ServiceHost sh=new ServiceHost(typeof(MyService)))
{
sh.Opened += delegate
{
Console.WriteLine("Service is ready......");
};
sh.Closed += delegate
{
Console.WriteLine("Service is closed");
};
sh.Open();
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
string SayHello();
}
public class MyService : IService
{
public string SayHello()
{
return "Hello Stranger";
}
}
App.config
<system.serviceModel>
<services>
<service behaviorConfiguration="Service1Behavior" name="VM1.MyService">
<endpoint address="" binding="netTcpBinding" bindingConfiguration="mybinding" contract="VM1.IService" >
</endpoint>
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:13007/"/>
</baseAddresses>
</host>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="mybinding">
<security mode="None">
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="Service1Behavior">
<serviceMetadata />
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Client end.
ServiceReference1.ServiceClient client = new ServiceReference1.ServiceClient();
try
{
Console.WriteLine(client.SayHello());
}
catch (Exception)
{
throw;
}
App.config
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="NetTcpBinding_IService">
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
<client>
<!--we may need to change the generated endpoint address to autual server IP address.-->
<endpoint address="net.tcp://10.157.13.69:13007/" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_IService" contract="ServiceReference1.IService"
name="NetTcpBinding_IService" />
</client>
</system.serviceModel>
Feel free to let me know if there is anything I can help with.
I added the following code and it works:
client.ClientCredentials.Windows.ClientCredential.UserName = runAs;
client.ClientCredentials.Windows.ClientCredential.Password = runAsPassword;
client.ClientCredentials.Windows.ClientCredential.Domain = runAsDomain;
However, I'd like to do this without security since it will be placed on multiple servers, none of which will have a public IP. I've tried to add to the bindings but on the client it's not a valid node and on the server, it stops the service from starting. I tried to add the following code to the server but it won't open the ServiceHost:
serviceHost.AddServiceEndpoint(typeof(eTutorWcfService), new NetTcpBinding(SecurityMode.None), "");
I can live with this but would really like to know how to do it without security.
Is it possible to call a WCF service from a universal application?
I added a service reference and the proxy was generated just fine.
But when creating a NetTcpBinding programmatically and passing that to the proxy's constructor the service model throws the exception PlatformNotSupported.
Both running the app in the simulator and on the local machine generates the same exception.
An exception of type 'System.PlatformNotSupportedException' occurred
in System.Private.ServiceModel.dll but was not handled in user code
"this operation is not supported"
EndpointAddress address = new EndpointAddress("net.tcp://test:9000/ServicesHost/PublishService");
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
PublishingService.PublishClient proxy = new PublishingService.PublishClient(binding, address);
Does anybody have an example of a working WCF client in a UAP?
EDIT
It has something to do with the service being a duplex service!
The original contract:
[ServiceContract(CallbackContract = typeof(IPublishCallback))]
public interface IPublish { }
After removing the CallbackContract attribute the UAP client can create a connection, so basic WCF works.
So I guess it's better to rephrase the question.
Is it possible to create a duplex WCF client in a universal application?
edit servicemodel for the host
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="netTcpPublishService" openTimeout="00:00:10" receiveTimeout="infinite">
<reliableSession inactivityTimeout="24.20:31:23.6470000" enabled="true" />
<security mode="Transport">
<transport clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="serviceBehaviour" name="PublishService.Publish">
<endpoint binding="mexHttpBinding" name="mexPublishService"
contract="IMetadataExchange" />
<endpoint address="PublishService" binding="netTcpBinding" bindingConfiguration="netTcpPublishService"
name="netTcpPublishService" contract="PublishService.IPublish" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8004/ServicesHost/PublishService" />
<add baseAddress="net.tcp://localhost:9004/ServicesHost/PublishService" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
Yes, it is possible. This is how i connect in a sample app i did a while ago:
using Tradeng.Srvc.Client.WinAppSimple.SrvcRefTradeng;
private InstanceContext instanceContext;
private TradengSrvcClientBase serviceProxy;
instanceContext = new InstanceContext(this);
serviceProxy = new TradengSrvcClientBase(instanceContext);
bool result = await serviceProxy.ConnectAsync();
if (result)
{
// connected...
}
I used the binding from the config file that is generated when you add a reference to your service.
This is what the app looks like. Cutting edge stuff.... :O)
https://www.youtube.com/watch?v=YSg6hZn1DpE
The service itself is running as a WebRole on Azure, by the way.
I have one application server implementing a bunch of services using default transferMode="Buffered" and one Streamed service. It exposes endpoints for basicHttp and net.tcp protocols, and runs in production under dozens of IIS 7.0+ configurations without incident.
When I went to replicate the architecture for a new application's server, streaming over net.tcp simply refused to work, throwing the perfectly opaque and obtuse ProtocolException
The .Net Framing mode being used is not supported by MyNetTcpEndpointAddress. See the server logs for more details.
Yeah right, the "server logs". (There's nothing, whether traced or not.) Service architectures and web.configs for S1 and S2 are identical, except for
some name changes
a custom namespace in S2 (S1 using tempuri)
different ports (S1 and S2 both using ports in the 8000-9000 range)
Streaming service S2 works just fine under basicHttp.
Having tried everything and failed to make the error go away, I built a test client that does nothing but run my service architecture with some Ping methods. No custom namespace, no frills, just the original configs, and lite services, contracts, and hand-coded wrappers around the ChannelFactory proxies.
Same error:
The .Net Framing mode being used is not supported by 'net.tcp://localhost:9931/StreamingService.svc'. See the server logs for more details.
The buffered test service works under both protocols, and the streamed service works under basicHttp, as in S2.
All testing done on the same Win7 machine with a complete IIS setup. The test app is still too big to post here, but here are the complete configs, and the console code
web.config
<configuration>
<connectionStrings>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<!-- throttling of stream size is partially controlled by this setting -->
<httpRuntime maxRequestLength="1048576" /><!-- 1GB -->
</system.web>
<system.serviceModel>
<serviceHostingEnvironment>
<serviceActivations>
<add relativeAddress="FooService.svc" service="WcfTest.Services.FooService" />
<add relativeAddress="StreamingService.svc" service="WcfTest.Services.StreamingService" />
</serviceActivations>
</serviceHostingEnvironment>
<behaviors>
<serviceBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="200000" />
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding
openTimeout="00:20:00" sendTimeout="00:20:00" receiveTimeout="00:20:00" closeTimeout="00:20:00"
maxBufferSize="20000000" maxBufferPoolSize="20000000" maxReceivedMessageSize="20000000">
<readerQuotas maxStringContentLength="12000" />
</binding>
<binding name="WcfTest.Streaming.Http" transferMode="Streamed"
openTimeout="03:00:00" sendTimeout="03:00:00" receiveTimeout="03:00:00" closeTimeout="03:00:00"
maxReceivedMessageSize="1073741824" /><!-- 1GB -->
</basicHttpBinding>
<netTcpBinding>
<binding
openTimeout="00:20:00" sendTimeout="00:20:00" receiveTimeout="00:20:00" closeTimeout="00:20:00"
maxBufferSize="20000000" maxBufferPoolSize="20000000" maxReceivedMessageSize="20000000">
<readerQuotas maxStringContentLength="12000" />
</binding>
<binding name="WcfTest.Streaming.Tcp" transferMode="Streamed"
openTimeout="03:00:00" sendTimeout="03:00:00" receiveTimeout="03:00:00" closeTimeout="03:00:00"
maxReceivedMessageSize="1073741824"><!-- 1GB -->
</binding>
</netTcpBinding>
</bindings>
<protocolMapping>
<add scheme="http" binding="basicHttpBinding" />
<add scheme="net.tcp" binding="netTcpBinding"/>
</protocolMapping>
<services>
<service name="WcfTest.Services.Streaming">
<!-- http -->
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="WcfTest.Streaming.Http" contract="WcfTest.Contracts.IStreamingService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<!-- net.tcp -->
<endpoint address="" binding="netTcpBinding" bindingConfiguration="WcfTest.Streaming.Tcp" contract="WcfTest.Contracts.IStreamingService" />
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
</configuration>
app.config
<configuration>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="200000"/>
</behavior>
<behavior name="customQuotaBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding
openTimeout="00:20:00" sendTimeout="00:20:00" receiveTimeout="00:20:00" closeTimeout="00:20:00"
maxBufferSize="20000000" maxBufferPoolSize="20000000" maxReceivedMessageSize="20000000">
<readerQuotas maxStringContentLength="12000" />
</binding>
<binding name="WcfTest.Bindings.Streaming.Http" transferMode="Streamed"
openTimeout="03:00:00" sendTimeout="03:00:00" receiveTimeout="03:00:00" closeTimeout="03:00:00"
maxReceivedMessageSize="1073741824"><!-- 1GB -->
</binding>
</basicHttpBinding>
<netTcpBinding>
<binding
openTimeout="00:20:00" sendTimeout="00:20:00" receiveTimeout="00:20:00" closeTimeout="00:20:00"
maxBufferSize="20000000" maxBufferPoolSize="20000000" maxReceivedMessageSize="20000000">
<readerQuotas maxStringContentLength="12000" />
</binding>
<binding name="WcfTest.Bindings.Streaming.Tcp" transferMode="Streamed"
openTimeout="03:00:00" sendTimeout="03:00:00" receiveTimeout="03:00:00" closeTimeout="03:00:00"
maxReceivedMessageSize="1073741824"><!-- 1GB -->
</binding>
</netTcpBinding>
</bindings>
<client>
<!-- Foo -->
<endpoint name="WcfTest.Endpoints.Foo.Http" address="http://localhost:9930/FooService.svc" binding="basicHttpBinding" contract="WcfTest.Contracts.IFooService" />
<endpoint name="WcfTest.Endpoints.Foo.Tcp" address="net.tcp://localhost:9931/FooService.svc" binding="netTcpBinding" contract="WcfTest.Contracts.IFooService" />
<!-- Streaming -->
<endpoint name="WcfTest.Endpoints.Streaming.Http" address="http://localhost:9930/StreamingService.svc" binding="basicHttpBinding" bindingConfiguration="WcfTest.Bindings.Streaming.Http" contract="WcfTest.Contracts.IStreamingService" />
<endpoint name="WcfTest.Endpoints.Streaming.Tcp" address="net.tcp://localhost:9931/StreamingService.svc" binding="netTcpBinding" bindingConfiguration="WcfTest.Bindings.Streaming.Tcp" contract="WcfTest.Contracts.IStreamingService" />
</client>
</system.serviceModel>
</configuration>
console test call
static void Main(string[] args)
{
Console.WriteLine("starting WcfTest client...");
Console.WriteLine();
PingFoo(Contracts.Enums.Protocol.Http);
PingFoo(Contracts.Enums.Protocol.Tcp);
Console.WriteLine();
PingStreaming(Contracts.Enums.Protocol.Http);
// only this call errors:
PingStreaming(Contracts.Enums.Protocol.Tcp);
Console.WriteLine();
Console.Write("ENTER to exit WcfTest client...");
Console.ReadLine();
}
private static bool PingFoo(Contracts.Enums.Protocol protocol)
{
FooProxy pxy = new FooProxy(protocol);
return PingProxy<IFooService>(pxy, protocol);
}
private static bool PingStreaming(Contracts.Enums.Protocol protocol)
{
StreamingProxy pxy = new StreamingProxy(protocol);
return PingProxy<IStreamingService>(pxy, protocol);
}
private static bool PingProxy<T>(ProxyServiceBase<T> pxy, Contracts.Enums.Protocol protocol) where T : IServiceBase
{
bool success = pxy.Ping();
Console.WriteLine("ping {0} {1}: {2}", pxy.GetType().Name, protocol, success ? " success" : " FAILED");
if (pxy != null)
pxy.Close();
return success;
}
Any ideas why this would be failing on one IIS site, under one of two protocols, and not on another? (It is not this.)
EDIT: In preparation for taking this bounty-side, a couple clarifications on this test service and client:
First, per commenter's suggestion, svcutil works fine against http, but fails against net.tcp. Here is the complete output of that run:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin>svcutil
net.tcp://localhost:9931/StreamingService.svc Microsoft (R) Service
Model Metadata Tool [Microsoft (R) Windows (R) Communication
Foundation, Version 3.0.4506.2152] Copyright (c) Microsoft
Corporation. All rights reserved.
Attempting to download metadata from
'net.tcp://localhost:9931/StreamingService.svc' using WS-Metadata
Exchange. This UR L does not support DISCO. Microsoft (R) Service
Model Metadata Tool [Microsoft (R) Windows (R) Communication
Foundation, Version 3.0.4506.2152] Copyright (c) Microsoft
Corporation. All rights reserved.
Error: Cannot obtain Metadata from
net.tcp://localhost:9931/StreamingService.svc
If this is a Windows (R) Communication Foundation service to which you
have access, please check that you have enabled m etadata publishing
at the specified address. For help enabling metadata publishing,
please refer to the MSDN documentat ion at
http://go.microsoft.com/fwlink/?LinkId=65455.
WS-Metadata Exchange Error
URI: net.tcp://localhost:9931/StreamingService.svc
Metadata contains a reference that cannot be resolved: 'net.tcp://localhost:9931/StreamingService.svc'.
The socket connection was aborted. This could be caused by an error processing your message or a receive timeout bei ng exceeded by
the remote host, or an underlying network resource issue. Local socket
timeout was '00:04:59.9929993'.
An existing connection was forcibly closed by the remote host
If you would like more help, type "svcutil /?"
Second, removing "transferMode="Streamed" from the Wcf.Bindings.Streaming.Tcp web and app configs pasted above allows the service to ping just fine. It does not improve the svcutil situation.
Finally, here are some other things I have tried, with no improvement:
Various versions of serviceMetadata attribute in serviceBehaviors (which I understand to be overridden by the existence of mex endpoints anyway)
Various named serviceBehaviors instead of the default I include
Various configurations of security mode= on the binding, especially None
Various disablings of all other bindings, endpoints, etc. in hopes that one thing might be getting in another's way
It seems that transferMode of tcp communication either at service side or client side to Streamed and the other side still uses the default mode which is Buffered.
Are you forgetting something in "StreamingProxy" in case of TCP?
May be this will help...
http://social.msdn.microsoft.com/Forums/vstudio/en-US/37e32166-63f3-4cb9-ab81-14caa50cd91e/help-with-error-message-the-net-framing-mode-being-used-is-not-supported-by-?forum=wcf
Also I am trying looking further for your solution...
I have a WCF service hosted by a Windows Service. It works but calling it is very slow: A simple function like void Test() takes around 500 ms from client call to server receive.
I tried several different configurations but haven't succeeded in making that faster. Both client and server are on the same machine.
Here is the code:
Shared.dll:
[ServiceContract]
public interface IContract
{
[OperationContract]
void Test();
}
Server.exe:
public class Service : IContract
{
public void Test()
{
this.Log("Test: " + DateTime.Now.TimeOfDay);
}
}
Client.exe:
var binding = ...;
var factory = new ChannelFactory<IContract>(binding, "net.tcp://localhost/Service");
var service = factory.CreateChannel();
this.Log("Test: " + DateTime.Now.TimeOfDay);
service.Test();
app.config:
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Server.Service">
<endpoint address="Service" binding="netTcpBinding" bindingConfiguration="NetTcp" contract="Shared.IContract">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost/" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="NetTcp" portSharingEnabled="true">
<security mode="None">
<message clientCredentialType="None"/>
<transport protectionLevel="None" clientCredentialType="None"/>
</security>
<reliableSession enabled="false" />
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Edit
I am currently testing this with client and server in the same machine but the idea is to have them in different machine for production.
The factory and channel creations are not the culprit here. I ruled that out putting a Thread.Sleep(20000) between the creation and the log and got the same result.
The difference between the client log and the server log is around 500 ms for the first call (actually, it's anywhere between 300 ms and 1 second) but then, it lasts less than 5 ms for any more call to Test(). I want my function to be always very fast, including the first call. How can I do that?
Assuming you are using the Datetime.Now's to measure this, I would recommend a different approach for benchmarking.
var elapsedTimes = new List<long>();
var stopwatch = new Stopwatch();
for (var i = 0; i < 1000; i++)
{
stopwatch.Reset();
stopwatch.Start();
service.Test();
stopwatch.Stop();
elapsedTimes.Add(stopwatch.ElapsedMilliseconds);
}
Log("Average time for Test(): " + elapsedTimes.Average() + "ms");
Also, the first call always seems to be slow, probably because of initializations taking place on the service side. Try making one call to service.Test() and then running this benchmark.
Please post your results, I'd be curious to found out how it goes.
this is a problem I have encountered that I'm completely clueless about. I have defined an IWorkerServiceContract class, as follows:
[ServiceContract]
public interface IWorkerServiceContract
{
[OperationContract]
int Test(int test);
}
Nothing special, I just wanted to test connectivity. Here is my service class:
class WorkerService : IWorkerServiceContract
{
public static ILogger Logger { get; set; }
public int Test(int test)
{
return test + 1;
}
public static ServiceHost Listen(Uri baseAddress)
{
ServiceHost host = new ServiceHost(typeof(WorkerService), baseAddress);
try
{
host.Open();
Logger.WriteLine("Listening at address: " + baseAddress.ToString());
}
catch (Exception e)
{
Logger.WriteLine("An exception was thrown, reason: {0}", e.Message);
}
return host;
}
}
The logger object is instantiated by an initializer class, it basically logs to a console allocated with AllocConsole(). When I invoke Listen(), everything works fine, and I'm able to connect via WCF test client and remotely invoke the Test() method. Although, when I define a proxy:
public partial class WorkerProxy : ClientBase<IWorkerServiceContract>,
IWorkerServiceContract
{
public WorkerProxy(EndpointAddress remoteAddress) :
base("workerEndpoint", remoteAddress)
{ }
public WorkerProxy(Uri remoteAddress) :
base("workerEndpoint", new EndpointAddress(remoteAddress))
{ }
public WorkerProxy(string remoteAddress) :
base("workerEndpoint", new EndpointAddress(remoteAddress))
{ }
public int Test(int test)
{
return base.Channel.Test(test);
}
}
And use the following code:
WorkerService.Listen("net.tcp://localhost:19000/dcalc");
WorkerProxy wp = new WorkerProxy("net.tcp://localhost:19000/dcalc");
wp.Test(0);
the application freezes! Here's my app.config file:
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding messageEncoding="Mtom" maxReceivedMessageSize="10485760">
<readerQuotas maxArrayLength="10485760" />
</binding>
</wsHttpBinding>
<netTcpBinding>
<binding maxReceivedMessageSize="10485760">
<readerQuotas maxArrayLength="10485760" />
</binding>
</netTcpBinding>
</bindings>
<services>
<service name="DCalc.Manager.ManagerService" behaviorConfiguration="managerServiceBehavior">
<endpoint address="" binding="wsHttpBinding" contract="DCalc.Common.IManagerServiceContract"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
<service name="DCalc.Worker.WorkerService" behaviorConfiguration="workerServiceBehavior">
<endpoint address="" binding="netTcpBinding" contract="DCalc.Common.IWorkerServiceContract"/>
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
</service>
</services>
<client>
<endpoint address="" binding="netTcpBinding" contract="DCalc.Common.IWorkerServiceContract" name="workerEndpoint" />
<endpoint address="" binding="wsHttpBinding" contract="DCalc.Common.IManagerServiceContract" name="managerEndpoint" />
</client>
<behaviors>
<serviceBehaviors>
<behavior name="managerServiceBehavior">
<serviceMetadata httpGetEnabled="true" policyVersion="Policy15"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="workerServiceBehavior">
<serviceMetadata policyVersion="Policy15"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
What I don't understand is that, as you can see, I have defined a ManagerService, and the application can connect to it without any problems. It doesn't seem to be a protocol problem, I'm getting the same result with wsHttpBinding.
What am I doing wrong?
The reason you saw your app was frozen because of a thread deadlock, which means that two threads lock each other when executing a portion of code/ accessing a common resource.
In this case:
On the client side, when the worker proxy thread calls Test(0), it will wait for the response to come back.
On the "server side", the server thread at the same time tries to take control and return the result. Because of thread affinity between the two threads, the server thread will wait until the worker thread finishes, but the worker thread is waiting for the response, so none of them could go further, and deadlock happens.