我是一个Windows服务的初学者,我有一个控制台应用程序用于在客户端和服务器之间传输文件。现在我想将我的服务器应用程序转换为Windows服务以便同时监听多个客户端。我将我的控制台应用程序代码放置在onstart()中。但是,在部署Windows服务后,它无法正常工作或监听。有什么建议吗?
我是一个Windows服务的初学者,我有一个控制台应用程序用于在客户端和服务器之间传输文件。现在我想将我的服务器应用程序转换为Windows服务以便同时监听多个客户端。我将我的控制台应用程序代码放置在onstart()中。但是,在部署Windows服务后,它无法正常工作或监听。有什么建议吗?
你好,我知道这个问题已经存在很久了,我查看了许多关于StackOverflow或其他网站的文章,但没有一个让我满意。最头疼的是:它是一个Windows服务,在服务启动时监听器的while循环不应该被阻塞。
最终,我自己想出了一个解决方案,也许不太友好,但非常简单并且正常工作(我同时打开了3个telnet到这个服务器,并且它按照我的期望工作):-)
`protected override void OnStart(string[] args)
{
tcpServerStart();
}
private void tcpServerStart()
{
try
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
//port 5555, or any port number you want
listener = new TcpListener(ipAddress, 5555);
listener.Start();
var whileThread = new Thread(() =>
{
while (true)
{
// in order to avoid while loop turn into an infinite loop,
// we have to use AcceptTcpClient() to block it.
TcpClient client = listener.AcceptTcpClient();
// for each connection we just fork a thread to handle it.
var childThread = new Thread(() =>
{
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream(); // not blocking call
StreamReader streamreader = new StreamReader(client.GetStream(), Encoding.ASCII);
string line = null;
// below while loop is your logic code, change it to your needs.
// defined "<EOF>" as mine quit message
while ((line = streamreader.ReadLine()) != "<EOF>")
{
// WriteToFile is a function of mineto log system status
WriteToFile(line);
}
stream.Close();
client.Close();
});
childThread.Start();
} // end of while(true) loop
});
whileThread.Start();
}
catch (Exception e)
{
}
} '
此服务器开启线程,否则无法运行服务。
protected override void OnStart(string[] args)
{
TcpServer server=new TcpServer();
server.Start();
}
class TcpServer
{
// clase prar crear un listener
private TcpListener server;
private bool isRunning;
private int port = 13000;
public void Start()
{
// client found.
// create a thread to handle communication
Thread tServer = new Thread(new ParameterizedThreadStart(StartThread));
tServer.Start();
}
public void StartThread(object o)
{
//iniciar configuraciones
Configuracion.init();
// crear un nuevo servidor
server = new TcpListener(IPAddress.Any, port);
//inicializar el servidor
server.Start();
//variable para indicar queesta corriendo el server
isRunning = true;
LoopClients();//thread
}}
public void LoopClients()
{
while (isRunning)
{
// wait for client connection
TcpClient newClient = server.AcceptTcpClient();
// client found.
// create a thread to handle communication
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}