我创建了这样的服务:
private SocketDataRepository socketRepository = new SocketDataRepository();
SerivceIPconfigRepository serivceIPconfigRepository=new SerivceIPconfigRepository();
public AsyncCallback pfnWorkerCallBack;
private Socket m_mainSocket;
private Socket[] m_workerSocket = new Socket[25];
private int m_clientCount = 0;
private string ipaddress;
protected override void OnStart(string[] args)
{
ServiceIpConfig serviceIpConfig = serivceIPconfigRepository.GetAll().First();
DrawMapPersian();
ipaddress = serviceIpConfig.IncomingIP;
// Check the port value
string portStr = serviceIpConfig.IncomingPort;
int port = System.Convert.ToInt32(portStr);
// Create the listening socket...
m_mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
// Bind to local IP Address...
m_mainSocket.Bind(ipLocal);
// Start listening...
m_mainSocket.Listen(4);
// Create the call back for any client connections...
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
protected override void OnContinue()
{
base.OnContinue();
}
protected override void OnStop()
{
}
正如您所看到的,我的服务会侦听端口以获取传入的数据。我还为我的服务添加了一个安装程序,如您所见:
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
public MyWindowsServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//set the privileges
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.DisplayName = "My Service";
serviceInstaller.StartType = ServiceStartMode.Manual;
//must be the same as what was set in Program's constructor
serviceInstaller.ServiceName = "My Service";
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
}
}
我使用installutil.exe
安装我的服务。一切正常,我的服务已安装,我可以在服务列表中看到它。但是当我尝试启动时,我收到了这个错误:
我检查了日志事件,我的错误是这样的:
Provider
[ Name] My Service
- EventID 0
[ Qualifiers] 0
Level 2
Task 0
Keywords 0x80000000000000
- TimeCreated
[ SystemTime] 2014-08-17T15:38:21.000000000Z
EventRecordID 7526
Channel Application
Computer ehsan-PC
Security
- EventData
Service cannot be started. The service process could not connect to the service controller
我的问题在哪里?