求教一个socket连接问题 为什么下面这段代码 客户端请求连接一次 服务端会多产生5个多线程啊?急求解啊
/// <summary>
/// 开始监听客户端的Socket请求
/// </summary>
private void StartListening()
{
try
{
if (this.listener != null)
{
//if (this.listener.Blocking)
//{
// this.listener.Blocking = false;
//}
this.listener.Dispose();
this.listener.Close();
logger.Info("关闭SocketServer成功(开始)!");
}
//byte[] bytes = new Byte[1024];
DataTable dt = new DataTable("ipTable");
dt.ReadXml(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)+@"\IpSetting.xml");
IPAddress ipAddress = IPAddress.Parse(dt.Rows[1][1].ToString());//dt.Rows[1][1].ToString()); // 127.0.0.1
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Convert.ToInt32(ClientContext.Instance.SocketPort));
this.listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create a TCP/IP socket.
//this.listener.
this.listener.Bind(localEndPoint); //绑定
this.listener.Listen(Convert.ToInt32(ClientContext.Instance.SocketPort)); //监听
while (this.isRun)
{
allDone.Reset(); //
logger.Info("Waiting for a connection..."); // Start an asynchronous socket to listen for connections.
//using (Socket clientSocket = this.listener.Accept())
//{
Socket clientSocket = this.listener.Accept();//创建一个新的Socket连接
td = new Thread(new ParameterizedThreadStart(this.AcceptCallback));
//接受客户端请求并进行验票操作
td.Name = "Socket" + SocketCount.ToString();
SocketCount++;
td.IsBackground = true;
logger.Info("线程ID号"+td.ManagedThreadId );
list.Add(td);
td.Start(clientSocket);
allDone.WaitOne();
//} // 等待线程-这将引起等待线程无限期的阻塞并等待类来通知。
}
if (this.listener != null) //终止“Socket服务器端”
{
this.listener.Dispose();
this.listener.Close();
logger.Info("关闭SocketServer成功(结束)!");
}
}
catch (Exception ex)
{
logger.Info(" 开始监听客户端的Socket请求时发生异常,原因是:" + ex.ToString());
}
}