SignalR從。。。到。。。


Signal搭建一個聊天室。

Signal框架學習

1.引入NuGut包
ASPNET.net.Signal.Hubs

新建一個owin startup類
代碼:

 public void Configuration(IAppBuilder app)
        {
            // 有關如何配置應用程序的詳細信息,請訪問 http://go.microsoft.com/fwlink/?LinkID=316888
           // ConfigureAuth(app);
            var hubConfiguration = new HubConfiguration();

            hubConfiguration.EnableDetailedErrors = true;
            GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(8);
            app.MapSignalR(hubConfiguration);
        }

2.新建一個集線器signalR類

思路:
服務端寫法 :


   public void Send(@1) (string Message)
   {
       //發(fā)送給所有客戶端
       Client.All.broadcastMessage(@2)(message);
   }

客戶端調(diào)用方法:

 new 一個 IHubProxy  hub;

 ///創(chuàng)建一個連接
 var connection = new HubConnection("Hub服務地址(調(diào)試的時候一般為 localhost:端口)”);

 ///調(diào)用服務端方法的接口
 hub = connection.Create("Hub類名");  


 客戶端調(diào)用方式:
 ///這部分相當于注冊事件
 hub.On("@2",(返回數(shù)據(jù))=>{ 返回數(shù)據(jù)的處理 });

 hub.Invoke("@1",參數(shù));//這步相當于觸發(fā)事件。

服務端代碼

  public class ChatHub : Hub
    {


        public static List<string> Onlineusers = new List<string>();

        public static List<string> messageCache = new List<string>();
        /// <summary>
        /// 廣播消息
        /// </summary>
        /// <param name="username"></param>
        /// <param name="message"></param>     
        
        public void Send(string SendID,string message)
        {
            Clients.All.broadcastMessage(Context.ConnectionId, message);
            messageCache.Add(Context.ConnectionId + message);
            //Clients.All.refresh()
           // Clients.All.addMessage(username + message);
            
        }


        public void p2p(string ReciveID,string SendID,string SendMessage)
        {

            
            Clients.Client(ReciveID).sendP2pMessage(ReciveID, SendMessage);
            messageCache.Add(SendID + "發(fā)送了" + SendMessage + "給" + ReciveID);
            
        }


        /// <summary>
        /// 獲取信息列表。詳細看客戶端。
        /// </summary>
        /// <param name="clinetID"></param>
        public void GetMesList(string clinetID)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in messageCache)
            {
                sb.AppendLine(item);

            }
            Clients.Client(clinetID).SendList(sb.ToString());

        }
        /// <summary>
        /// 獲取用戶列表
        /// </summary>
        /// <returns></returns>

        public void GetOnline(string ClientID)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in Onlineusers)
            {
                sb.Append("*"+item);
            }
            Clients.Client(ClientID).SendUserList(sb.ToString());
        }
        public override Task OnConnected()
        {
            Onlineusers.Add(Context.ConnectionId);
            Clients.All.broadcastMessage(Context.ConnectionId, "加入了服務器");

            StringBuilder sb = new StringBuilder();
            foreach (var item in Onlineusers)
            {
                sb.Append("*" + item);
            }
            Clients.All.SendUserList(sb.ToString());
            Clients.All.broadcastMessage("當前在線人數(shù)", Onlineusers.Count + "人");
            return base.OnConnected();
        }

        public override Task OnDisconnected(bool stopCalled)
        {
            Onlineusers.Remove(Context.ConnectionId);
            Clients.All.broadcastMessage(Context.ConnectionId, "離開了服務器");
            StringBuilder sb = new StringBuilder();
            foreach (var item in Onlineusers)
            {
                sb.Append("*" + item);
            }
            Clients.All.SendUserList(sb.ToString());
            Clients.All.broadcastMessage("當前在線人數(shù)", Onlineusers.Count + "人");
            return base.OnConnected();
        }



    }

客戶端代碼:

 public partial class Form1 : Form
    {


        /// <summary>
        /// hub句柄
        /// </summary>
        IHubProxy hub;
        string name = "";

        public Form1()
        {
            InitializeComponent();
            

        }
    

        private void button1_Click(object sender, EventArgs e)
        {
            var connection = new HubConnection(textBox1.Text);
            hub = connection.CreateHubProxy(textBox2.Text);

            connection.Error += error => MessageBox.Show(error.ToString());
            try
            {
                connection.Start().Wait();
                name = connection.ConnectionId;
                hub.On<string, string>("broadcastMessage", (m, s) =>
                {
                  
                        textBoxRecive.Invoke(new MethodInvoker(() => { this.textBoxRecive.AppendText(m +"說:"+s + "\r\n"); }));
                });

                hub.On<string, string>("sendP2pMessage", (c, m) =>
                {
                    textBoxRecive.Invoke(new MethodInvoker(() => { this.textBoxRecive.AppendText(c+"說:"+m + "\r\n"); }));
                });



                hub.On<string>("SendUserList", (listvalue) =>
                {
                    textBoxRecive.Invoke(new MethodInvoker(() =>
                    {
                      
                        string[] str = listvalue.Trim().Split('*');
                        List<string> values = new List<string>();
                        textBoxDic.AppendText("當前在線用戶 :" + "\r\n");
                        foreach (var item in str)
                        {
                            if(item!="")
                            {
                                values.Add(item);
                                textBoxDic.AppendText(item + "\r\n");
                            }

                        }
                        
                        comboBox1.DataSource = values;
                        comboBox1.SelectedIndex = 0;
                        
                    }));

                });

                ///這里是觸發(fā)該次回調(diào)的調(diào)用過程。
                hub.Invoke("GetOnline", name);

                // hub.Invoke("Send", "", name);

                MessageBox.Show("連接成功!");
                label4.Text = name;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }



        /// <summary>
        /// 表示調(diào)用信息列表。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            

            ///這里可以理解為注冊回調(diào)。 listValue為回調(diào)的接收data.
            hub.On<string>("SendList", (listvalue) =>
             {
                 textBoxRecive.Invoke(new MethodInvoker(() =>
                 {
                     textBoxDic.AppendText("緩存數(shù)據(jù)" + "\r\n" + listvalue+"\r\n");
                 }));

             });

            ///這里是觸發(fā)該次回調(diào)的調(diào)用過程。
           hub.Invoke("getMesList",name);


        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (radioButton2.Checked)
            {
                ///發(fā)送點對點消息 第一個參數(shù) 接收者ID 第二個參數(shù) 發(fā)送ID 第三個參數(shù) 發(fā)送內(nèi)容。
                hub.Invoke("p2p", comboBox1.Text, name, textBoxSend.Text);

            }
            else
            {
                hub.Invoke("Send", name, this.textBoxSend.Text);
            }
           
        }

        private void button3_Click(object sender, EventArgs e)
        {
            hub.Invoke("Send", "測試數(shù)據(jù)");
        }


       
    }

Web頁面客戶端簡單實現(xiàn):

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <div id="mineID"></div>
        <ul id="discussion"></ul>
    </div>
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/jquery.signalR-2.2.1.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>    
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.

            //var name = chat.client.connection.oncl
            //$('#mineID').append("<p>" + name + "</p>");

            var name;
            chat.client.broadcastMessage = function (username, message) {
                // Html encode display name and message.
                var encodedName = $('<div />').text(username).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#discussion').append('<li><strong>' + encodedName
                    + '</strong>:  ' + encodedMsg + '</li>');
            };

          

             
           
            // Get the user name and store it to prepend to messages.
            //$('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            //$('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>

————————————————————————————————我是有底線的———————————————————————————————————————

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評論 19 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,979評論 25 709
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內(nèi)部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,651評論 18 399
  • 嗨,米娜!話說今兒個一早,寶寶的朋友圈就被出行高峰給霸屏了,然而,對于想要脫單甚至已經(jīng)脫單的我們來說,這點阻礙算什...
    咖唄橙閱讀 429評論 2 3
  • 很多事情只有在具體的實踐當中才能真正明白其中的含義,很多人只有經(jīng)歷過很多傷痛之后才能真正明白其中的道理,沒有誰可以...
    千夜凡塵閱讀 645評論 0 0

友情鏈接更多精彩內(nèi)容