2015-01-06 67 views
1

我使用SignalR進行服務器和客戶端之間的雙向通信,服務器和客戶端都使用Win應用程序。如何從服務器發送數據到特定的客戶端ID在winForm按鈕點擊SIgnalR

服務器端我在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

首先添加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)) 
       )) 
      ); 

//顯示消息我希望這幫助

+0

感謝它的工作。 – Adam

2

在signalr您可以使用groups的概念,因爲狀態默認情況下丟失。要發送消息到特定的客戶端,您可以map users to connections

+0

是的,我知道團體的概念。在小型演示中似乎很難實現。我只需要做一個測試演示。 – Adam

+0

嗨塔裏克。組很容易使用,但不是很有活力。將用戶映射到連接的自定義實現是我將使用的。請注意,自從您使用桌面客戶​​端http://www.asp.net/signalr/overview/getting-started/supported-platforms以來,您將需要win8 +和.NET 4.5才能使用Websockets。 – Uffe

相關問題