WCF / Windows服务无法正常工作

时间:2011-07-25 16:29:52

标签: wcf dll windows-services

我正在尝试与WCF一起创建Windows服务。我们不想使用IIS来处理服务的代理。我已经注册并启动了服务。我创建了一个简单的控制台应用程序来调用服务,但它超时了。

我有一个.NET DLL,其中包含调用本地运行的应用程序来创建警报记录的函数。我创建了一个使用AlarmLib.dll的表单应用程序,它可以进行调用并插入警报记录。

这似乎是一个权限问题。我得到以下异常:

> Unhandled Exception: System.ServiceModel.EndpointNotFoundException:
> Could not co nnect to http://localhost:8000/ServiceModel/service. TCP
> error code 10061: No co nnection could be made because the target
> machine actively refused it 127.0.0.1:
> 8000.  ---> System.Net.WebException: Unable to connect to the remote
> server --->  System.Net.Sockets.SocketException: No connection could
> be made because the tar get machine actively refused it
> 127.0.0.1:8000
> at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
> SocketAddre ss socketAddress)    at
> System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)    at
> System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
> Sock et s4, Socket s6, Socket& socket, IPAddress& address,
> ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout,
> Exception& exception)    --- End of inner exception stack trace
> at System.Net.HttpWebRequest.GetRequestStream(TransportContext&
> context)    at System.Net.HttpWebRequest.GetRequestStream()    at
> System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStre
> am()    --- End of inner exception stack trace ---

我以管理员身份运行VS2010。我可以修改的服务的其他任何设置?

谢谢, 约翰

Windows服务代码:

using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.Configuration;
using System.Configuration.Install;
using AlarmLib;

namespace Test.ServiceModel

.WindowsServices {



        // 

Define a service contract.
    [ServiceContract(Namespace = "http://ServiceModel.WindowsServices")]
    public interface IAlarmLib {
        [OperationContract]
        bool CreateNoDataAlarm(string well, string run, string record, string description, string selectedVariable);
    }

    // Implement the IAlarmLib service contract in a service class.
    public class AlarmLibService : IAlarmLib {
        // Implement the IAlarmLib methods.


    public bool CreateNoDataAlarm(string well, string run, string record, string description, string sel

ectedVariable) {
            AlarmUserConfiguration newalarm = new AlarmUserConfiguration();

            // The Machine name should be the machine which is running the client application
            // and which calls the webservice. This should not be the name of machine hosting

        // webservice.
        newalarm.MachineName = System.Environment.MachineName;
        newalarm.AlarmType = AlarmTypes.NoData;
        newalarm.TimeInSeconds = 30;
        DateTime CreationTime = DateTime.Now;
        newalarm.Name = "NoDataAlarm " + CreationTime.ToString();
        PrimaryKey key = new PrimaryKey();
        key.Well = "Well ID 1";
        key.Run = "1600";
        key.Record = "DGR";
        key.Desc = "Realtime";
        key.SelectedVariable = "Gamma Ray A";
        newalarm.PrimaryKeys = key;

        // Add any of the following activities.
        /*"All"
        "Trip Out"
        "Trip In"
        "Circulating"
        "Drilling On Bottom"
        "Drilling Off Bottom"*/

        newalarm.TDActivities.Add("Drilling On Bottom");

        bool bStatus = AlarmUtilities.AddNewAlarm(newalarm, "-Local-");
        return bStatus;
    }
}

public class AlarmLibWindowsService : ServiceBase {
    public ServiceHost serviceHost = null;
    public AlarmLibWindowsService() {
        // Name the Windows Service
        ServiceName = "AlarmLibWS";
    }

    public static void Main() {
        ServiceBase.Run(new AlarmLibWindowsService());
    }

    // Start the Windows service.
    protected override void OnStart(string[] args) {
        if (serviceHost != null) {
            serviceHost.Close();
        }

        // Create a ServiceHost for the AlarmLibService type and 
        // provide the base address.
        serviceHost = new ServiceHost(typeof(AlarmLibService));

        // Open the ServiceHostBase to create listeners and start 
        // listening for messages.
        serviceHost.Open();
    }

    protected override void OnStop() {
        if (serviceHost != null) {
            serviceHost.Close();
            serviceHost = null;
        }
    }
}

// Provide the ProjectInstaller class which allows 
// the service to be installed by the Installutil.exe tool
[RunInstaller(true)]
public class ProjectInstaller : Installer {
    private ServiceProcessInstaller process;
    private ServiceInstaller service;

    public ProjectInstaller() {
        process = new ServiceProcessInstaller();


          process.Account = ServiceAccount.LocalSystem;
            service = new ServiceInstaller();
            service.ServiceName = "AlarmLibWS";
            Installers.Add(process);
            Installers.Add(service);
        }
    }
}

App.config中:

    <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <!-- This section is optional with the new configuration model
           introduced in .NET Framework 4. -->
      <service name="ServiceModel.WindowsServices.AlarmLibService" behaviorConfiguration="AlarmLibServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/ServiceModel/service"/>
          </baseAddresses>
        </host>
        <!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/ServiceModel/service  -->
        <endpoint address=""
                  binding="wsHttpBinding"
                  contract="ServiceModel.WindowsServices.IAlarmLib" />
        <!-- the mex endpoint is exposed at http://localhost:8000/ServiceModel/service/mex -->
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="AlarmLibServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

控制台应用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestAlarmLibConsoleApp {
    class Program {
        static void Main(string[] args) {
            ServiceReference1.AlarmLibClient client = new ServiceReference1.AlarmLibClient();
            bool result = client.CreateNoDataAlarm("Well ID 1", "1100", "DGR", "Realtime", "Gamma Ray A");
            Console.WriteLine("result = " + bool.TrueString);
        }
    }
}

以下是有效的表单应用中的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using AlarmLib;

namespace TestCallingAlarmLib {
    static class Program {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool result = CreateNoDataAlarm();

            Application.Run(new Form1());
        }

        static bool CreateNoDataAlarm() {
            AlarmUserConfiguration newalarm = new AlarmUserConfiguration();

            // The Machine name should be the machine which is running the client application
            // and which calls the webservice. This should not be the name of machine hosting
            // webservice.
            newalarm.MachineName = System.Environment.MachineName;
            newalarm.AlarmType = AlarmTypes.NoData;
            newalarm.TimeInSeconds = 30;
            DateTime CreationTime = DateTime.Now;
            newalarm.Name = "NoDataAlarm " + CreationTime.ToString();
            PrimaryKey key = new PrimaryKey();
            key.Well = "Well ID 1";
            key.Run = "1100";
            key.Record = "DGR";
            key.Desc = "Realtime";
            key.SelectedVariable = "Gamma Ray A";
            newalarm.PrimaryKeys = key;

            // Add any of the following activities.
            /*"All"
            "Trip Out"
            "Trip In"
            "Circulating"
            "Drilling On Bottom"
            "Drilling Off Bottom"*/

            newalarm.TDActivities.Add("Drilling On Bottom");

            bool bStatus = AlarmUtilities.AddNewAlarm(newalarm, "-Local-");
            return bStatus;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

检查您的客户端访问策略,确保在服务器上打开了端口并仔细检查防火墙。每次我收到这个错误都与其中一个有关。

相关问题