前面已经贴了Socket的基本编程要点和步骤,这里继续贴一下关于异步Socket通信的代码。
using System.Net ;
using System.Net.Sockets ;
using System.IO ;
using System.Text ;
using System.Threading ;
public static ManualResetEvent allDone = new ManualResetEvent(false);
private Thread th;
private bool listenerRun = true ;
Socket listener;
private const int MAX_SOCKET=10;
protected override void Dispose( bool disposing )
{
try
{
listenerRun = false ;
th.Abort ( ) ;
th = null ;
listener.Close();
}
catch { }
}
//得到本机IP地址
//得到本机IP地址
public static IPAddress GetServerIP()
{
IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());
return ieh.AddressList[0];
}
//侦听方法
private void Listen()
{
try
{
int nPort=int.Parse(this.txtLocalPort.Text);
IPAddress ServerIp=GetServerIP();
IPEndPoint iep=new IPEndPoint(ServerIp,nPort);
listener=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
listener.Bind(iep);
listener.Listen(10);
statusBar1.Panels[0].Text ="端口:"+this.txtLocalPort.Text+"正在监听......";
while(listenerRun)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
allDone.WaitOne();
}
}
catch (System.Security.SecurityException )
{
MessageBox.Show ("防火墙安全错误!","错误",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
//异步回调函数
public void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
Socket client=listener.EndAccept(ar) ;
allDone.Set();
StateObject state = new StateObject();
state.workSocket = client;
//远端信息
EndPoint tempRemoteEP = client.RemoteEndPoint;
IPEndPoint tempRemoteIP = ( IPEndPoint )tempRemoteEP ;