|
之前飞哥发了一个同步的版本,我来个异步的吧.{:soso_e113:}(只写了tcp,udp懒得写了.)
http://www.sufeinet.com/thread-3678-1-1.html
注释都写了.过程也理清楚了.完全当学习的东西看吧..
- <P>/*
- 说明:Socket辅助类
- 作者:Ro4ters
- 编写时间: 26-06-2013
- 主要功能:
- 接收发送数据.(异步)</P>
- <P>*/
- class SocketHelper
- {
- public delegate void Uplistbox(string txt);
- public Uplistbox uplb; //更新listbox委托变量
- protected static readonly ILog logger = LogManager.GetLogger(typeof(TCPSocketServer2));
- private ManualResetEvent allDone = new ManualResetEvent(false); //线程控制
- protected Hashtable m_workerSocketHt = Hashtable.Synchronized(new Hashtable());//保存客户端socket哈希表
- public AsyncCallback asyncCallBack; //声明异步完成时调用的方法.
- private Socket m_mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//主通信Socket
- public bool isExit = false;//全局控制SOCKET启动和关闭
- private long m_clientCount = 0L;//记录客户端数量
- /// <summary>
- /// 发送消息
- /// </summary>
- /// <param name="buffer">需要发送的字节</param>
- public void Send(byte[] buffer)
- {
- try
- {
- //目标地址
- IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
- //发送通信socket
- Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- sk.Connect(ip);//连接
- sk.Send(buffer);//发送
- SocketUser su = new SocketUser();
- su.CurrentSocket = sk;
- su.DataBuffer = buffer;
- //异步接收
- asyncCallBack = new AsyncCallback(OnDataReceived);
- sk.BeginReceive(su.DataBuffer, 0, su.DataBuffer.Length, SocketFlags.None, asyncCallBack, su);</P>
- <P> }
- catch (Exception ex)
- {
- string msg = ex.ToString() + " " + DateTime.Now.ToString();
- uplb(msg);
- logger.Debug(msg);
- }
- }
- /// <summary>
- /// 发送消息[重载]
- /// </summary>
- /// <param name="SocketUser">需要发送的SocketUser对象</param>
- /// <param name="buffer">需要发送的字节</param>
- public void Send(SocketUser su, byte[] buffer)
- {
- try
- {
- //目标地址
- IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
- //发送通信socket
- su.CurrentSocket.Connect(ip);//连接
- su.CurrentSocket.Send(buffer);//发送
- su.DataBuffer = buffer;
- //异步接收
- asyncCallBack = new AsyncCallback(OnDataReceived);
- su.CurrentSocket.BeginReceive(su.DataBuffer, 0, su.DataBuffer.Length, SocketFlags.None, asyncCallBack, su);</P>
- <P> }
- catch (Exception ex)
- {
- string msg = ex.ToString() + " " + DateTime.Now.ToString();
- uplb(msg);
- logger.Debug(msg);
- }
- }
- /// <summary>
- /// 建立监听连接
- /// </summary>
- /// <param name="port">监听的端口号</param>
- private void AcceptConnection(object port)
- {
- try
- {</P>
- <P> IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, (int)port);
- //绑定地址
- m_mainSocket.Bind(ipLocal);
- //开始监听
- m_mainSocket.Listen(10000);
- while (isExit == false)
- {
- try
- {
- allDone.Reset(); //线程阻塞
- logger.Debug("TcpListener启动成功: " + ipLocal.Address.ToString() + "," + ipLocal.Port.ToString());
- //接收异步连接并创建新的socket对象.
- m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), m_mainSocket);
- allDone.WaitOne();
- }
- catch (SocketException sf)
- {
- logger.Error("客户连接请求异常" + sf.ToString());
- }
- catch (Exception f)
- {
- logger.Error("客户连接请求异常" + "错误信息:" + f.Message);
- break;
- }</P>
- <P> }
- }
- catch (SocketException se)
- {
- logger.Error("TcpListener启动失败" + se.ToString() + "错误号:" + se.ErrorCode.ToString());</P>
- <P> }
- catch (Exception e)
- {
- logger.Error("TcpListener错误" + "错误信息:" + e.Message);
- }</P>
- <P> }
- /// <summary>
- /// 开始监听
- /// </summary>
- /// <param name="Port">监听的端口</param>
- /// <param name="buffer">发送的字节</param>
- public bool StartListening(int Port, params byte[] buffer)
- {
- if (Port == 0)
- {
- logger.Debug("TcpListener未启动,请指定监听的端口号.");
- return false;
- }</P>
- <P> // 创建监听socket
- Thread AcceptTh = new Thread(new ThreadStart(delegate
- {
- AcceptConnection(Port);
- }));
- AcceptTh.Start();
- Thread sendth = new Thread(new ThreadStart(delegate
- {
- Send(buffer);
- }));
- sendth.Start();
- logger.Debug("启动TCP监听,端口: " + Port);
- return true;
- }</P>
- <P>//下面方法在二楼
- }
- }</P>
- <P> </P>
复制代码 Have Fun; {:soso_e121:}
26-06-2013
|
|