如何在winForm SIgnalR中单击按钮时将数据从服务器发送到特定客户端ID

时间:2015-01-06 12:18:44

标签: signalr

我正在使用SignalR进行服务器和客户端之间的双向通信,服务器和客户端都在使用Win应用程序。

服务器端我在DropDownlist中添加了所有连接的客户端ID,现在我想做两件事。

1)我想从下拉列表中选择客户端ID,然后在按钮点击时将字符串发送到选定的客户端。

我的服务器端在这里:

private void buttonClient_Click(object sender, EventArgs e)
        {
         // here i want write code for send data to selected client .
          string Clientid = comboBoxClients.SelectedItem.ToString();

        }

public class MyHub : Hub
    {
 public void Send(string name, string message){ Clients.All.addMessage(name, message);}
    }

我的客户端代码:

private void ButtonSend_Click(object sender, EventArgs e)
        {
            HubProxy.Invoke("Send", UserName, TextBoxMessage.Text);
            TextBoxMessage.Text = String.Empty;
            TextBoxMessage.Focus();
        }

2 个答案:

答案 0 :(得分:2)

首先添加IhubContext的全局对象。

IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();



private void buttonClient_Click(object sender, EventArgs e)
        {
            string Clientid = comboBoxClients.SelectedItem.ToString();
// sendOrders(string,string) this method should make on client side with same name  and here call like thats . 
            context.Clients.Client(Clientid).sendOrders("Name","Message Server to you"); 

        }

//我的客户端代码: //创建并连接集线器连接和集线器代理,并调用方法名称SendOrders。 //在consolewindow中显示消息

HubProxy.On<string, string>("sendOrders", (name, myString) =>
             this.Invoke((Action)(() =>
                    RichTextBoxConsole.AppendText(String.Format("{0}: {1}" + Environment.NewLine, name, myString))
                ))
            );

我希望这个帮助

答案 1 :(得分:2)

在signalr中,您可以使用groups的概念,因为默认情况下缺少状态。要向特定客户发送消息,您可以map users to connections

相关问题