C#:一个增强的TcpListener(二)线程池
2012-05-10 10:11
369 查看
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Threading; namespace Splash.Net.Sockets { public partial class TcpListenerPlus : TcpListener { /// <summary> /// 委托声明 /// </summary> /// <param name="sender">事件发送者</param> /// <param name="e">事件参数</param> public delegate void ThreadTaskRequest(object sender, EventArgs e); /// <summary> /// 线程任务请求事件 /// </summary> public event ThreadTaskRequest OnThreadTaskRequest; // 已接受的Tcp连接列表 protected List<TcpClient> _tcpClients; /// <summary> /// 连接列表操作互斥量 /// </summary> private Mutex _mutexClients; /// <summary> /// 侦听连接线程 /// </summary> private void ListenThreadAction() { // 启动侦听 Start(); // 初始化连接列表和互斥量 _tcpClients = new List<TcpClient>(); _mutexClients = new Mutex(); // 接受连接 while (true) { TcpClient tcpClient = null; try { // 接受挂起的连接请求 tcpClient = AcceptTcpClient(); // 将该连接通信加入线程池队列 ThreadPool.QueueUserWorkItem(ThreadPoolCallback, tcpClient); // 连接加入列表 _mutexClients.WaitOne(); _tcpClients.Add(tcpClient); _mutexClients.ReleaseMutex(); } catch (SocketException) { // 结束侦听线程 break; } catch (Exception) { // 加入队列失败 if (tcpClient != null) { tcpClient.Close(); } } } } /// <summary> /// 线程池回调方法 /// </summary> /// <param name="state">回调方法要使用的信息对象</param> private void ThreadPoolCallback(Object state) { // 如果无法进行转换,则 as 返回 null 而非引发异常 TcpClient tcpClient = state as TcpClient; try { // 执行任务 if (OnThreadTaskRequest != null) { OnThreadTaskRequest(tcpClient, EventArgs.Empty); } } catch { // 阻止异常抛出 } finally { // 关闭连接 tcpClient.Close(); // 从列表中移除连接 _mutexClients.WaitOne(); if (_tcpClients != null) { _tcpClients.Remove(tcpClient); } _mutexClients.ReleaseMutex(); } } /// <summary> /// 关闭侦听器 /// </summary> /// <remarks>显示隐藏从基类继承的成员</remarks> public new void Stop() { // 检测是否已开启侦听 if (Active) { // 关闭侦听器 base.Stop(); // 关闭已建立的连接 _mutexClients.WaitOne(); if (_tcpClients != null) { foreach (TcpClient client in _tcpClients) { client.Close(); } // 清空连接列表 _tcpClients.Clear(); _tcpClients = null; } _mutexClients.ReleaseMutex(); } } } }
相关文章推荐
- C#:一个增强的TcpListener(二)线程池
- C#:一个增强的TcpListener(一)构造函数
- C#:一个增强的TcpListener(*)服务器演示程序及源代码下载
- C#:一个增强的TcpListener(*)服务器演示程序及源代码下载
- C#:一个增强的TcpListener(一)构造函数
- [C#]使用TcpListener及TcpClient开发一个简单的Chat工具
- C#使用TcpListener及TcpClient开发一个简单的Chat工具实例
- C#:一个增强的TcpClient(六)数据加密
- C#:一个增强的TcpClient(*)客户端演示程序及源代码下载
- C#:一个增强的TcpClient(五)构造函数
- C#:一个增强的TcpClient(三)读取
- C#:一个增强的TcpClient(四)查询
- C# Socket TcpClient 无法从传输连接中读取数据: 远程主机强迫关闭了一个现有的连接。。
- (1) Socket网络编程(C#)----TcpListener 与 TcpClient
- Unity, C# ,TCP实现的一个简单的对话同步功能
- C#利用TcpListener和TcpClient类实现服务器和客户端的通信
- C# asynchronous TcpListener
- C#网络编程系列文章(四)之TcpListener实现同步TCP服务器
- c#制作一个TCP/UDP测试工具
- 常量,字段,构造方法 调试 ms 源代码 一个C#二维码图片识别的Demo 近期ASP.NET问题汇总及对应的解决办法 c# chart控件柱状图,改变柱子宽度 使用C#创建Windows服务 C#服务端判断客户端socket是否已断开的方法 线程 线程池 Task .NET 单元测试的利剑——模拟框架Moq