Some time ago, a client required me to develop a Web Service and Windows Service combined. I started searching on the internet for possibilities and stumbled across this great tutorial.
I started a new Windows Service and followed all the steps in the tutorial. All compiled well and I started my Windows Service (and with that, the Web Service). However, as soon as I tried to connect to the Web Service, I received an error message "Server actively refused connection".
Let me tell a little background story about the requirements for the product. The Windows Service would run on the machine that has the IP that has a DNS entry [ServiceName].[Company].com. I wanted to start the Web Service on localhost (since I was already on the right computer).
When you try to connect to soap.tcp://localhost:[port]/[ServiceName], it will succeed. However, as soon as you try to connect to soap.tcp://[ServiceName].[Company].com/MyService, you will receive the actively refused error. When you run netstat -a, it will show you that the Web Service is listening at the right port, but why isn't it working?
The solution is that you cannot directly connect to soap.tcp://[ServiceName].[Company].com/MyService. You should first resolve the DNS entry and then connect to that result using the following code:
///
/// Initializes the soap service listener
///
private void InitializeServiceListener()
{
try
{
// Create address
string address = string.Format("soap.tcp://{0}:{1}/{2}",
Dns.GetHostAddresses(Dns.GetHostName())[0],
Settings.Default.ServicePort, Settings.Default.ServiceName);
// Create SOAP listener & endpoint
Uri addressUri = new Uri(address);
// Start hosting the web service
SoapReceivers.Add(new EndpointReference(addressUri), typeof(CommandListener));
// Log
EventLogHelper.EventLog.WriteEntry(address, EventLogEntryType.Information);
}
catch (Exception ex)
{
// Log
EventLogHelper.EventLog.WriteEntry(string.Format(Resources.ErrorInitializingWebservice, ex.Message),
EventLogEntryType.Error);
}
}
As you see, you should get the hostname of the current computer to start the service. The address will be exactly the same as when you type it, but now it will work.
For the client side, you should do the same:
// Set up server
MyService server = new MyService ();
server.Url = string.Format("soap.tcp://{0}:{1}/[ServiceName]",
Dns.GetHostEntry("[ServiceName].[Company].com").AddressList[0], Settings.Default.ServicePort);
Now the Web Service inside the Windows Service will work as planned.