|
-
October 8th, 2005, 10:44 AM
#9
Re: Selective events
OK here is the sample. It selectively sends event to the clients. It does not have any comment . So, if you have any question, please feel free to post it here. This code compiles and runs fine. You can improve the server method to invoke any delegate.
Code:
class Client
{
private int clientID = -1;
public Client(int clientID)
{
this.clientID = clientID;
}
public int ClientID
{
get { return clientID; }
set { clientID = value; }
}
public void MyTestEventHandler(object sender, TestEventArgs eventArgs)
{
System.Console.WriteLine("Client " + clientID.ToString() + " is called");
}
static void Main(string[] args)
{
// create server object
Server server = new Server();
// create client objects.
Client c1 = new Client(1);
Client c2 = new Client(2);
// clients adds event handler to the events they are interested in.
server.SelectiveEvent += new MyTestEvent(c1.MyTestEventHandler);
server.SelectiveEvent += new MyTestEvent(c2.MyTestEventHandler);
// call server method to selectively invoke the clients
server.InvokeClients(new int[] { 2 }, new TestEventArgs());
}
}
public class Server
{
public event MyTestEvent SelectiveEvent;
public void InvokeClients(int[] clientIDs, TestEventArgs args)
{
if ((clientIDs != null) && (clientIDs.Length > 0))
{
foreach (MyTestEvent eventDelegate in SelectiveEvent.GetInvocationList())
{
Client targetObject = eventDelegate.Target as Client;
// loop thro' the array and see whether the client is in the id list.
// there are better way to do it if you don't want to loop for every client.
// this will give you an idea.
for (int index = 0; index < clientIDs.Length; index++)
{
if (targetObject.ClientID == clientIDs[index])
{
eventDelegate(this, args);
break;
}
}
}
}
}
}
/// <summary>
/// TestEventArgs
/// </summary>
public class TestEventArgs : EventArgs
{
// Some Event args here.
}
/// <summary>
/// Delegate declaration
/// </summary>
public delegate void MyTestEvent(object sender, TestEventArgs eventArgs);
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|