2011-04-14 58 views
0

这是我的代码到目前为止。我有主客户连接时动态创建的主窗体和wcf对象。现在所有的wcf对象都订阅从主窗体中触发的事件。仅将事件触发到特定的动态对象?

然而,我希望用户能够从主窗体的组合框中选择一个名称,并将一个事件仅发送给提交此名称的wcf对象。

你认为做这件事的最好方法是什么?

谢谢!

namespace server2 
{ 
    public partial class Form2 : Form 
    { 
     public Form2() 
     { 
      InitializeComponent(); 
     } 

     public event EventHandler sendEvnt; 
     private ServiceHost duplex; 

     private void Form2_Load(object sender, EventArgs e)  /// once the form loads, create and open a new ServiceEndpoint. 
     { 
      duplex = new ServiceHost(typeof(ServerClass)); 
      duplex.AddServiceEndpoint(typeof(IfaceClient2Server), new NetTcpBinding(), "net.tcp://localhost:9080/service"); 
      duplex.Open(); 
      this.Text = "SERVER *on-line*"; 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      sendEvnt(this, new EventArgs()); 
      // this send an event to all WCF objects 
      // what should I do for it to send an event ONLY to the wcf object, that's name is selected from the comboBox ? 
     } 
    } 


    class ServerClass : IfaceClient2Server 
    { 

     IfaceServer2Client callback; 

     public ServerClass() 
     { 
      callback = OperationContext.Current.GetCallbackChannel<IfaceServer2Client>(); 
     } 

     public void StartConnection(string name) 
     { 
      var myForm = Application.OpenForms["Form2"] as Form2; 

      myForm.comboBox1.Items.Add(name); 
      myForm.comboBox1.SelectedItem = name; // adds a name to form's comboBox. 

      myForm.sendEvnt += new EventHandler(eventFromServer); // somehow need to incorporate the 'name' here. 

      callback.Message_Server2Client("Welcome, " + name); 
     } 

     void eventFromServer(object sender, EventArgs e) 
     { 
      var myForm = Application.OpenForms["Form2"] as Form2; 
      string msg = myForm.tb_send.Text; 
      if (msg == "") { msg = "empty message"; } 
      callback.Message_Server2Client(msg); 
     } 

     public void Message_Cleint2Server(string msg) 
     { 
     } 

     public void Message2Client(string msg) 
     { 
     } 

    } 




    [ServiceContract(Namespace = "server", CallbackContract = typeof(IfaceServer2Client), SessionMode = SessionMode.Required)] 


    public interface IfaceClient2Server   ///// what comes from the client to the server. 
    { 
     [OperationContract(IsOneWay = true)] 
     void StartConnection(string clientName); 

     [OperationContract(IsOneWay = true)] 
     void Message_Cleint2Server(string msg); 
    } 


    public interface IfaceServer2Client   ///// what goes from the sertver, to the client. 
    { 
     [OperationContract(IsOneWay = true)] 
     void AcceptConnection(); 

     [OperationContract(IsOneWay = true)] 
     void RejectConnection(); 

     [OperationContract(IsOneWay = true)] 
     void Message_Server2Client(string msg); 
    } 

} 

回答

2

WCF对象是如何存储的?我假设你将它们存储在某种集合中。如果是这种情况,请尝试将您的收藏改为Dictionary<string, WcfObjectType>。从那里你可以根据用户输入的字符串查找字典中的对象。

相关问题