如:
public delegate void DisconnectedEventHandler(object sender,ClientEventArgs e);
2.定义事件参数
如:
public class ClientEventArgs : EventArgs
{
public IPAddress IP
{
get { return ( (IPEndPoint)this.socket.RemoteEndPoint ).Address; }
}
public int Port
{
get{return ((IPEndPoint)this.socket.RemoteEndPoint).Port;}
}
public ClientEventArgs(Socket clientManagerSocket)
{
this.socket = clientManagerSocket;
}
}
{
public IPAddress IP
{
get { return ( (IPEndPoint)this.socket.RemoteEndPoint ).Address; }
}
public int Port
{
get{return ((IPEndPoint)this.socket.RemoteEndPoint).Port;}
}
public ClientEventArgs(Socket clientManagerSocket)
{
this.socket = clientManagerSocket;
}
}
3.使用"代表"定义一个事件
public event DisconnectedEventHandler Disconnected;
4.触发事件
protected virtual void OnDisconnected(ClientEventArgs e)
{
if ( Disconnected != null )
Disconnected(this , e);
}
this.OnDisconnected(new ClientEventArgs(this.socket));
{
if ( Disconnected != null )
Disconnected(this , e);
}
this.OnDisconnected(new ClientEventArgs(this.socket));
5.使用事件
ClientManager newClientManager = new ClientManager(socket);
newClientManager.Disconnected += new DisconnectedEventHandler(ClientDisconnected);
newClientManager.Disconnected += new DisconnectedEventHandler(ClientDisconnected);
6.定义事件处理方法
void ClientDisconnected(object sender , ClientEventArgs e)
{
if ( this.RemoveClientManager(e.IP) )
this.UpdateConsole("Disconnected." , e.IP , e.Port);
}
{
if ( this.RemoveClientManager(e.IP) )
this.UpdateConsole("Disconnected." , e.IP , e.Port);
}