【问题标题】:C# listen to two tcp port at a same timeC#同时监听两个tcp端口
【发布时间】:2019-02-20 23:51:21
【问题描述】:

我打开两个 tcp 端口来监听我的服务器的客户端。下面是我打开端口的代码。我用一个线程:

            clientThreadTS = new Thread(ClientListenerTS);
            clientThreadTS.IsBackground = true;
            clientThreadTS.Name = "client listener TS";
            clientThreadTS.Start();

            clientThreadDis = new Thread(ClientListenerDis);
            clientThreadDis.IsBackground = true;
            clientThreadDis.Name = "client listener Dis";
            clientThreadDis.Start();

客户端监听函数:

        private void ClientListenerTS()
    {
        try
        {
            if (bRestartListener)
            {
                Debug.WriteImportant("Restart QS listener");
                bRestartListener = false;
                htTCPClientTS.Clear();

                if (theClientListener != null)
                {
                    try
                    {
                        theClientListener.Close();
                    }
                    catch (Exception ex2)
                    {
                    }
                }
                theClientListener = null;

            }

            if (theClientListener == null)
            {
                try
                {
                    Debug.WriteImportant("Creating listener for client TS at any local IPs - port " + nConstClientPortTS);

                    IPEndPoint localEP = new IPEndPoint(IPAddress.Any, nConstClientPortTS);
                    theClientListener = new Socket(localEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    theClientListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    theClientListener.Bind(localEP);
                    theClientListener.Listen(100);
                    theClientListener.BeginAccept(new AsyncCallback(AcceptConnectBackTS), theClientListener);

                }
                catch (Exception ex2)
                {
                    Debug.WriteLine(ex2.ToString());
                    System.Threading.Thread.Sleep(500);
                    theClientListener = null;
                }
            }

        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }

    private void ClientListenerDis()
    {
        try
        {
            if (bRestartListener)
            {
                Debug.WriteImportant("Restart QS listener");
                bRestartListener = false;
                htTCPClientDis.Clear();

                if (theClientListener != null)
                {
                    try
                    {
                        theClientListener.Close();
                    }
                    catch (Exception ex2)
                    {
                    }
                }
                theClientListener = null;

            }

            if (theClientListener == null)
            {
                try
                {
                    Debug.WriteImportant("Creating listener for client display at any local IPs - port " + nConstClientPortDis);


                    IPEndPoint localEP = new IPEndPoint(IPAddress.Any, nConstClientPortDis);
                    theClientListener = new Socket(localEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    theClientListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    theClientListener.Bind(localEP);
                    theClientListener.Listen(100);
                    theClientListener.BeginAccept(new AsyncCallback(AcceptConnectBackDis), theClientListener);

                }
                catch (Exception ex2)
                {
                    Debug.WriteLine(ex2.ToString());
                    System.Threading.Thread.Sleep(500);
                    theClientListener = null;
                }
            }

        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }
    }

问题总是只是第一个端口成功打开。第二个端口没有打开。

代码是否正确编写?打开第一个端口后是否需要延迟再打开另一个端口?

知道为什么只打开第一个端口吗?

【问题讨论】:

  • 能否分享ClientListenerTSClientListenerDis函数?
  • 我已经编辑了我的问题... clientlistenerts 和 clientlistenerdis 差不多
  • 一模一样?同一个端口?我不确定我是否完全理解您要执行的操作。如果此链接有帮助,请告诉我:*.com/a/19387431/6819902
  • 不...它的两个不同端口... ClientListenerTS 端口 4000 和 ClientListenerDis 端口 4001
  • 我有点担心你的两种方法似乎都在使用一个名为theClientListener 的变量,但没有一个声明作为局部变量。这向我表明它可能是一个领域,而且他们可能都踩在 same 领域。

标签: c# .net multithreading sockets tcp


【解决方案1】:

您可以按照答案中的示例进行操作。

https://social.msdn.microsoft.com/Forums/vstudio/en-US/09828be4-6ac4-45ec-a116-508314dab793/listen-on-multiple-ports?forum=csharpgeneral

监听类:

class ListenPorts
{
    Socket[] scon;
    IPEndPoint[] ipPoints;

   internal ListenPorts(IPEndPoint[] ipPoints)
    {
        this.ipPoints = ipPoints;

        scon = new Socket[ipPoints.Length];
    }

    public void beginListen()
    {
        for (int i = 0; i < ipPoints.Length; i++)
        {
            scon[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            scon[i].Bind(ipPoints[i]);

            Thread thread = new Thread(threadListen);

            thread.Start(scon[i]);
        }
    }



    public void threadListen(object objs)
    {
        Socket scon = objs as Socket;
        byte[] data = new byte[1024];

        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

        EndPoint Remote = (EndPoint)(sender);

        try
        {
            scon.Listen(100);
            Socket newSocket = scon.Accept();
            newSocket.ReceiveFrom(data, ref Remote);
           // scon.ReceiveFrom(data, ref Remote);
        }

        catch (SocketException ex)
        {
            Console.WriteLine(ex.Message);
        }

       Console.WriteLine(scon.LocalEndPoint.ToString() + "IP {0}: ", Remote.ToString());
    }
}

调用类监听的方法:

    static void Main(string[] args)
    {
        IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
        IPEndPoint ipPoint1 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8081);

        IPEndPoint[] ipPoints = new IPEndPoint[2] { ipPoint, ipPoint1 };
        ListenPorts lp = new ListenPorts(ipPoints);

        Console.WriteLine("Begin Listen");

        lp.beginListen();
    }

【讨论】:

  • 请解释一下。仅仅一个链接并不是一个很好的答案。
  • 解释很好!