Tuesday, May 1, 2012

WCF Broadcast from Server example

lets say that i want to control from my computer (\machine) all the programs, that i create, of all the users in all the cpu's in our LAN...  so i need a server that all the programs will connect to him and he will be able to tell them to do stuff...  that sound like FUN! and i'll show it in WCF!

this is part 1 where i show how to broadcast from the server itself, no client invoking
part 2: http://bresleveloper.blogspot.com/2012/05/wcf-application-manager-example.html

WCF most simple server-client exmaple in the world ever:
and we want the server to do stuff so...
WCF most simple server-client callbacks exmaple in the world ever:
*the remebers:
     server telling client what to do is called a Callback
     client AND server both need to implement their own class each
     client AND server both need to know the both Interfaces (,not the classes)
so i used his example, added the string reverser a broadcast method and register:
void Broadcast(string msg);
bool Register();

thats it for the interface, and the class looks like this (all of it except method reverse string):

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,        
       ConcurrencyMode = ConcurrencyMode.Multiple)]
public class StringReverser : IStringReverser    
        List<ICallbacks> myClients = new List<ICallbacks>();        

        public bool Register()        
             ICallbacks newClient =
            return true;

       public void Broadcast(string msg)        
              foreach (ICallbacks client in myClients)            

the ICallback interface need this:
[OperationContract(IsOneWay=true)]void PrintMessage(string msg);

and the implementation - so simple:
public void PrintMessage(string msg)
      //or MessageBox.Show(msg) if u wanna try it in a winform
      //please notice that stuff like MessageBox that wait for a client operation
      //(click OK) stuck the server! to avoid this make a thread - see in part 2     

now..... how do we call it? thats the secret most tutorial dont tell you
you simply need to create the StringReverser object before creating the ServiceHost, keep the reference and sent the Ref to the host ctor (i marked the change with //):
static void Main(string[] args)        

       StringReverser serviceInstance = new StringReverser();
       using (ServiceHost host = new ServiceHost(
                 new Uri[] { new Uri("net.pipe://localhost") }))

                       new NetNamedPipeBinding(),

               Console.WriteLine("Broadcast your msg:");
               string msg = Console.ReadLine();
               serviceInstance.Broadcast("its a broadcast: " + msg);

               Console.WriteLine("Service is available. Press <ENTER> to exit.");

And there you go :D

1 comment:

  1. This website certainly has all the information and facts I wanted about
    this subject and didn't know who to ask.
    Also see my page - Recovery exchange server