本文介绍了Windows Service中的TCP IP侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Windows服务,该服务需要在后台运行并侦听传入流量(常规和常规TCP侦听器)

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)

我的代码是:

private TcpListener server;

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

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

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

表示我的服务从不使用Thread或Work方法.我从以前的日志记录中看到它进入了我的while循环,然后使服务超时

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

推荐答案

在您的 OnStart 方法中,您必须实例化服务器类.

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

负责通过创建新的 Thread 处理与服务器的连接(因此这是一个非阻塞过程)

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

对于每个将由 TCPListener 监听的套接字.

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

这是完整的项目文章.

这篇关于Windows Service中的TCP IP侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 07:41