0

I open two tcp ports for listening to client for my server. Below is my code for opening the port. I use a thread:

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

The client listener function:

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

The problem is always just the first port opened successfully. The second port does not opened.

Are the codes correctly written? Is it need some delay after opening the first port before we open another port?

Any idea why the first port only open?

Coolguy
  • 2,225
  • 12
  • 54
  • 81
  • Can you please share `ClientListenerTS` and `ClientListenerDis` functions? – DarkDiamonD Sep 17 '18 at 05:32
  • I have already edited my question... the clientlistenerts and clientlistenerdis is about the same – Coolguy Sep 17 '18 at 05:37
  • Exactly the same? same port? I'm not sure I fully understand what you are trying to do. Let me know if this link helps: https://stackoverflow.com/a/19387431/6819902 – DarkDiamonD Sep 17 '18 at 05:41
  • Nope... its two different port... Port 4000 for ClientListenerTS and port 4001 for ClientListenerDis – Coolguy Sep 17 '18 at 05:42
  • Are you getting an error while you are trying to open the second one? – DarkDiamonD Sep 17 '18 at 05:46
  • No error msg... When I use debug, no problem, two port created. But when I use the released version, only first port created... second port not created – Coolguy Sep 17 '18 at 05:47
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/180174/discussion-between-darkdiamond-and-coolguy). – DarkDiamonD Sep 17 '18 at 05:50
  • 1
    I'm kindof concerned that both of your methods seem to be using a variable called `theClientListener` but neither one *declares* that as a local variable. Which suggests to me that it may be a field and furthermore that they may both be stomping on the *same* field. – Damien_The_Unbeliever Sep 17 '18 at 05:55
  • Yup... I declares two different theClientListener and the problem solved – Coolguy Sep 17 '18 at 06:15

1 Answers1

-2

You can follow the examples in the answers.

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

Listener class:

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

Method to Invoke the class to Listen:

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