suppose i have small wcf service which has duplex connection and i want that no method will be callback at my client end rather a event should fire instead. then how to restructure my code. my code as follows.
server end
namespace CommonParts
{
[ServiceContract(Namespace = "rf.services",
CallbackContract = typeof(IDataOutputCallback),
SessionMode = SessionMode.Required)]
public interface IServerWithCallback
{
[OperationContract(IsOneWay=true)]
void StartDataOutput(string msg);
}
public interface IDataOutputCallback {
[OperationContract(IsOneWay = true)]
void SendDataPacket(string data);
}
}
namespace RF.WCF.Callback.Server
{
class ServerWCallbackImpl : IServerWithCallback
{
#region IServerWithCallback Members
public void StartDataOutput(string msg)
{
//OperationContext.Current.
IDataOutputCallback callback = OperationContext.Current.GetCallbackChannel<IDataOutputCallback>();
for (int i = 0; i < 10; i++)
{
Random r = new Random();
int interval = r.Next(500,3000);
System.Threading.Thread.Sleep(interval);
//callback.SendDataPacket("Packet " + i.ToString());
callback.SendDataPacket("Hello " + msg);
}
callback.SendDataPacket("Last packet is this one :)");
}
#endregion
}
}
class Program
{
static void Main(string[] args)
{
var myBinding = new NetTcpBinding(SecurityMode.None);
ServiceHost duplex = new ServiceHost(typeof(ServerWCallbackImpl));
duplex.AddServiceEndpoint(typeof(IServerWithCallback),
myBinding,
"net.tcp://192.168.1.2:9080/DataService");
duplex.Open();
Console.WriteLine("Host is running, press <ENTER> to exit.");
Console.ReadLine();
duplex.Close();
}
}
client end
class CallbackImpl : IDataOutputCallback
{
#region IDataOutputCallback Members
public void SendDataPacket(string data)
{
Console.WriteLine("Server sent: {0}", data);
}
#endregion
}
static void Main(string[] args)
{
var myBinding = new NetTcpBinding(SecurityMode.None);
DuplexChannelFactory<IServerWithCallback> cf =
new DuplexChannelFactory<IServerWithCallback>(
new CallbackImpl(),
myBinding,
new EndpointAddress("net.tcp://192.168.1.2:9080/DataService"));
IServerWithCallback srv = cf.CreateChannel();
Console.Write("Enter Value... ");
srv.StartDataOutput(Console.ReadLine());
Console.WriteLine("Start");
Console.ReadLine();
}
when this below line will be executed from client side called srv.StartDataOutput(Console.ReadLine());
then StartDataOutput() function will be called and from this function a callback function will be invoke called callback.SendDataPacket(“Hello ” + msg); then SendDataPacket() function will be called at client side.
so my question is how can i trigger a event at client side instead of callback function
A good tutorial for event-driven WCF asynchronous services is here at Code Project.
It should get you a good start on what you need done. One of the key statements made in this example is that the process is not too different from making a callback call. 🙂