【发布时间】: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());
}
}
问题总是只是第一个端口成功打开。第二个端口没有打开。
代码是否正确编写?打开第一个端口后是否需要延迟再打开另一个端口?
知道为什么只打开第一个端口吗?
【问题讨论】:
-
能否分享
ClientListenerTS和ClientListenerDis函数? -
我已经编辑了我的问题... clientlistenerts 和 clientlistenerdis 差不多
-
一模一样?同一个端口?我不确定我是否完全理解您要执行的操作。如果此链接有帮助,请告诉我:*.com/a/19387431/6819902
-
不...它的两个不同端口... ClientListenerTS 端口 4000 和 ClientListenerDis 端口 4001
-
我有点担心你的两种方法似乎都在使用一个名为
theClientListener的变量,但没有一个声明作为局部变量。这向我表明它可能是一个领域,而且他们可能都踩在 same 领域。
标签: c# .net multithreading sockets tcp