利用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

效果如下:

原文地址:https://www.cnblogs.com/CarzySunshine/p/14047816.html