eurekha_ananth
eurekha_ananth

Reputation: 151

how to setup a tcplistener in windows services c#

Iam beginner to windows services , i have a console application to transfer files between client and server . Now i would like to turn my server application into windows services for listening multiple clients . I placed my console application code inside onstart() . After deploying the windows services not working or listening . Any IQ's...

Upvotes: 3

Views: 20196

Answers (3)

Mike Xue
Mike Xue

Reputation: 31

hi i know this question is a long-standing one, and i checked many articles on stackoverflow or other sites, but there is no one make me satisfied. the most headache point is: it is a windows service, the while loop of listener should NOT be blocked when the service startup.

finally i made up a solution by myself, maybe maybe it is not system friendly, but it is quite simple and works fine ( I opened 3 telnet to this server concurrently, and it works as i wish) :-)

here is the code:

`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)
    {
    }
}  '  

Upvotes: 1

Hector Medina
Hector Medina

Reputation: 9

this server open thread else never running service

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);

        }
    }

Upvotes: 0

ABH
ABH

Reputation: 3439

Here is a complete article on TCP listener in windows service. It's quite old though but may be it helps.

Upvotes: 8

Related Questions