假设我有一个具有双工连接的小型 wcf 服务,并且我希望在我的客户端不会回调任何方法,而是应该触发一个事件。那么如何重组我的代码。我的代码如下。
服务器端
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();
}
}
客户端
class CallbackImpl : IDataOutputCallback
{ #region IDataOutputCallback 成员
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();
}
当下面这行将从客户端执行时调用srv.StartDataOutput(Console.ReadLine());
然后将调用 StartDataOutput() 函数,并从该函数调用一个回调函数,称为callback.SendDataPacket("Hello " + msg); 然后将在客户端调用SendDataPacket()函数。
所以我的问题是如何在客户端触发事件而不是回调函数