СОБЫТИЯ только для конкретного динамического объекта? - PullRequest
0 голосов
/ 14 апреля 2011

Вот мой код. У меня есть основная форма и объекты wcf, которые создаются динамически при подключении клиента. Сейчас все объекты wcf подписываются на события, запускаемые из главной формы.

Тем не менее, я хочу, чтобы пользователь мог выбрать имя из comboBox главной формы и запустить событие только для объекта 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);
    }

}

1 Ответ

2 голосов
/ 14 апреля 2011

Как хранятся объекты WCF?Я полагаю, вы храните их в какой-то коллекции.Если это так, попробуйте изменить свою коллекцию на Dictionary<string, WcfObjectType>.Оттуда вы можете искать объект в Словаре на основе введенной пользователем строки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...