1. 程式人生 > >最簡單的基於signalR客戶端服務端通訊

最簡單的基於signalR客戶端服務端通訊

首先建立一個asp.net專案,選擇MVC(空工程也可以),不要勾選儲存在雲上
 
然後再在服務端需要繼承寫一個類(假定叫CharHub.cs)並繼承Hub,並新增一個函式(這個函式就是WebAPI),如下
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace SignalRChat
{
    [HubName("Chat")]
    public class ChatHub : Hub
    {
        public void Send(string msg)
        {
            Clients.All.SendMessage(msg);
        }
    }
}
其次在服務端需要將這個WebAPI註冊,新增一個類StartUp.cs,並新增如下程式碼
using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}
至此服務端基本寫完了,然後就可以啟動這個Web工程了
啟動完成後記下網址,包括IP和埠。後續客戶端建立連線時需要使用這個地址

接下來的就是客戶端
建立一個WPF的應用程式
前臺程式碼如下
<Window x:Class="WpfApplication23.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication23"
        mc:Ignorable="d"
        Title="Client" Height="800" Width="620">
    <StackPanel>
        <TextBox x:Name="ShowMsg" Width="600" Height="500" IsReadOnly="True"/>
        <TextBox x:Name="Msg" Width="600" Height="100"/>
        <Button Width="100" Height="30" Content="傳送" Click="Button_Click"/>
    </StackPanel>
</Window>

後臺程式碼如下
using Microsoft.AspNet.SignalR.Client;
using System;
using System.Windows;

public partial class MainWindow : Window
    {
        private HubConnection _hubConnection;
        private IHubProxy _hubProxy;

        public MainWindow()
        {
            InitializeComponent();

            ReceiveInfomation += OnReceiveInfomation;

            _hubConnection = new HubConnection("http://localhost:23072");
            _hubProxy = _hubConnection.CreateHubProxy("Chat");
            _hubProxy.On<string>("sendMessage", (message) => ReceiveInfomation?.Invoke(message));

            _hubConnection.Start().ContinueWith(t =>
            {
                MessageBox.Show(t.IsFaulted ? string.Format("連線失敗!{0}", t.Exception.Message) : "連線成功!");
            }).Wait();
        }

        public delegate void ListenHandler(string msg);
        public event ListenHandler ReceiveInfomation = null;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _hubProxy.Invoke("Send", Msg.Text);
            Msg.Text = "";
        }

        private void OnReceiveInfomation(string message)
        {
            Dispatcher.BeginInvoke(new Action(delegate
            {
                string paragraph = string.Format("{0}  {1}\n", DateTime.Now, message);
                ShowMsg.Text += paragraph;
            }));
        }
    }
    首先初始化HubConnetion,傳入伺服器的地址,然後根據這個hunConnection建立一個通訊埠hubProxy,最後定義服務端回撥的函式SendMessage。
    初始化時冒號裡的函式名需與服務端對應,但是不區分大小寫(如chat,SendMessage和Send)
    初始化完成後就可以開始連線了,調_hubConnection.Start()開始連線,連線成功後即可發起通訊了。

    連線成功後,點選按鈕時,調_hubProxy.Invoke方法即可調到伺服器上對應的Send方法。把輸入的功能傳入到服務端,服務端接收到後通過Client.All.SendMessage
    呼叫所有申明瞭SendMessage方法的客戶端中的該方法,即可將msg傳到所有的客戶端中