TCP IP Listener in windows Service

房东的猫 提交于 2019-12-03 08:57:44

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();
  server.StartServer();
}

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_server.Start();
    m_serverThread = new Thread(new ThreadStart(ServerThreadStart));
    m_serverThread.Start();

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

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

private void ServerThreadStart()
{
  // Client Socket variable;
  Socket clientSocket = null;
  TCPSocketListener socketListener = null;
  while(!m_stopServer)
  {
    try
    {
      // 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.
      //Monitor.Enter(m_socketListenersList);
      lock(m_socketListenersList)
      {
        m_socketListenersList.Add(socketListener);
      }
      //Monitor.Exit(m_socketListenersList);

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

Here it is the full project article.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!