日期:2014-05-18 浏览次数:21078 次
/// <summary> /// 启动监听,轮询监听客户机请求并将客户端套接字存入转发表 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Listen() { IPAddress _ip = IPAddress.Any; Socket newsoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsoc.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); IPEndPoint locaEp = new IPEndPoint(IPAddress.Any, _port);//建立连接 try { newsoc.Bind(locaEp); newsoc.Listen(100); newsoc.BeginAccept(new AsyncCallback(onCall), newsoc);//异步监听回调 } catch (Exception ex) { DAL.Log.Write(DateTime.Now.ToString() + ex.ToString() + "\r\n\r\n"); } } /// <summary> /// 监听回调 /// </summary> /// <param name="ar"></param> private void onCall(IAsyncResult ar) { try { Socket serverSoc = (Socket)ar.AsyncState; Socket clent = serverSoc.EndAccept(ar); byte[] comes = new byte[1024]; EndPoint enp = clent.RemoteEndPoint; clent.Send(comes, comes.Length, 0); _transmit_tb.Add(clent.RemoteEndPoint, null); serverSoc.BeginAccept(new AsyncCallback(onCall), serverSoc); while (true) { byte[] buffer = new byte[1024]; int re = clent.Receive(comes); clent.Send(Encoding.ASCII.GetBytes("ok!")); string msg = Encoding.UTF8.GetString(comes, 0, re); string ip = clent.RemoteEndPoint.ToString(); if (msg.Length == 0) { _transmit_tb.Remove(clent.RemoteEndPoint); _receviccethread.Interrupt(); _receviccethread.Abort(); break;