1. 程式人生 > 實用技巧 >利用SignalR實現聊天室(進階篇)

利用SignalR實現聊天室(進階篇)

實現web與窗體程式通訊聊天

在原來的基礎上程式碼保持不變,窗體程式負責互動

 1   public partial class Form1 : Form
 2     {
 3         string url = "http://localhost:10319";
 4         HubConnection _conn;
 5         IHubProxy _proxy;
 6         string username = "wdd3";
 7         public Form1()
 8         {
 9             InitializeComponent();
10 CheckForIllegalCrossThreadCalls = false; 11 12 } 13 private void Form1_Load(object sender, EventArgs e) 14 { 15 _conn = new HubConnection(url, true); 16 _proxy = _conn.CreateHubProxy("MyHub"); 17 _conn.Start(); 18 setlogin();
19 } 20 private void setlogin() 21 { 22 _conn.StateChanged += new Action<StateChange>(tgt => 23 { 24 if (((StateChange)tgt).NewState == Microsoft.AspNet.SignalR.Client.ConnectionState.Connected) 25 { 26 //
客戶端呼叫服務端的 Send() 方法,傳入引數"Hello" 27 _proxy.Invoke("SendLogin", "wdd3"); 28 } 29 }); 30 31 //定義客戶端的方法sendMessage()(有兩個string型別的引數,當服務端呼叫sendMessage,需要傳入2個string型別引數),以這種格式定義方法服務端才能去呼叫 32 _proxy.On<string>("sendMessage123", rebackdata); 33 _proxy.On<string>("sendMessage_Persion", setmsg); 34 } 35 36 37 38 private void button1_Click(object sender, EventArgs e) 39 { 40 41 42 } 43 44 public void rebackdata(string s) 45 { 46 textBox3.Text =s.ToString(); 47 } 48 public void setmsg(string s) 49 { 50 textBox4.Text = s.ToString(); 51 } 52 53 private void button2_Click(object sender, EventArgs e) 54 { 55 _proxy.Invoke("SendByGroup", username, textBox2.Text, textBox1.Text); 56 //_conn.StateChanged += new Action<StateChange>(tgt => 57 //{ 58 // if (((StateChange)tgt).NewState == Microsoft.AspNet.SignalR.Client.ConnectionState.Connected) 59 // { 60 // //客戶端呼叫服務端的 Send() 方法,傳入引數"Hello" 61 62 // } 63 //}); 64 65 } 66 }
View Code

效果如下: