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?