Pilsneren Pilsneren - 2 months ago 38x
C# Question

TCP IP Listener in windows Service

I'm trying to create a windows service that needs to run in the background and listen for incoming traffic (a normal and regular TCP listener)

my code is:

private TcpListener server;

public void startServer()
// EventLog.WriteEntry(source, "connected on: " + ipAddress.ToString() + " port: " + Service1.Port.ToString());

server = new TcpListener(IPAddress.Parse(""), Service1.Port);

while (true)
var client = server.AcceptTcpClient();

new Thread(work).Start(client);


public void work(object client)
string msg = null;
var clientLocal = (TcpClient)client;

using (NetworkStream ns = clientLocal.GetStream())
using (StreamReader sr = new StreamReader(ns))
byte[] msgFullArray = new UTF8Encoding(true).GetBytes(msg);
fs.Write(msgFullArray, 0, msg.Length);

now if you don't look at the work method at all as whenever i start my service it freezes whenever i try to start it at my :

var client = server.AcceptTcpClient();

meaning my service never gets to use the Thread or my Work method..
i can see from previous logging that it enters my while loop and then just times out the service


In your OnStart Method you have to instantiate a server class.

protected override void OnStart(string[] args)
  // Create the Server Object ans Start it.
  server = new TCPServer();

that is responsible to handle the connections to the server by creating a new Thread (so that it is a non-blocking process)

public void StartServer()
  if (m_server!=null)
    // Create a ArrayList for storing SocketListeners before
    // starting the server.
    m_socketListenersList = new ArrayList();

    // Start the Server and start the thread to listen client 
    // requests.
    m_serverThread = new Thread(new ThreadStart(ServerThreadStart));

    // Create a low priority thread that checks and deletes client
    // SocktConnection objcts that are marked for deletion.
    m_purgingThread = new Thread(new ThreadStart(PurgingThreadStart));

for each socket that it will be listening by a TCPListener.

private void ServerThreadStart()
  // Client Socket variable;
  Socket clientSocket = null;
  TCPSocketListener socketListener = null;
      // Wait for any client requests and if there is any 
      // request from any client accept it (Wait indefinitely).
      clientSocket = m_server.AcceptSocket();

      // Create a SocketListener object for the client.
      socketListener = new TCPSocketListener(clientSocket);

      // Add the socket listener to an array list in a thread 
      // safe fashon.

      // Start a communicating with the client in a different
      // thread.
    catch (SocketException se)
      m_stopServer = true;

Here it is the full project article.