【问题标题】:Signalr:Connect to remote host through wpfSignalr:通过wpf连接远程主机
【发布时间】:2014-11-10 10:32:21
【问题描述】:

我已经制作了一个控制台应用程序,它作为信号 r 的主机并监听端口 8089。当我运行 wpf 应用程序并在 localhost 上运行该主机应用程序时,一切正常。现在我已经在服务器上部署了该控制台应用程序.现在当我尝试连接时,它没有通过 wpf 连接。所以后来我读到它只支持 HTTP 协议,读完之后我做了一个网站,它连接到远程服务器上的服务器,并且连接成功。我的问题是有什么方法可以使用 wpf 连接到该服务器。我想制作一个桌面聊天应用程序,其中所有客户端都将连接到同一服务器以便它可以广播。任何帮助将不胜感激

StartUp.CS

     public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                // Branch the pipeline here for requests that start with "/signalr"
                app.Map("/signalr", map =>
                {
                    // Setup the CORS middleware to run before SignalR.
                    // By default this will allow all origins. You can 
                    // configure the set of origins and/or http verbs by
                    // providing a cors options with a different policy.
                    map.UseCors(CorsOptions.AllowAll);
                    var hubConfiguration = new HubConfiguration
                    {
                        // You can enable JSONP by uncommenting line below.
                        // JSONP requests are insecure but some older browsers (and some
                        // versions of IE) require JSONP to work cross domain
                        // EnableJSONP = true
                    };
                    // Run the SignalR pipeline. We're not using MapSignalR
                    // since this branch already runs under the "/signalr"
                    // path.

                    hubConfiguration.EnableDetailedErrors = true;
                    map.RunSignalR(hubConfiguration);
                });
            }
        }


**Program.CS**


     class Program
        {
            static void Main(string[] args)
            {
                // This will *ONLY* bind to localhost, if you want to bind to all addresses
                // use http://*:8080 to bind to all addresses. 
                // See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx 
                // for more information.
                string url = "http://MyIpAddressOfServer:8089";
                using (WebApp.Start(url))
                {
                    Console.WriteLine("Server running on {0}", url);

                    Console.ReadLine();
                }
            }
        }

**MainWindowXaml.cs**

 public partial class MainWindow : Window
    {
        public System.Threading.Thread Thread { get; set; }
        public string Host = "http://MyIpAddressOfServer:8089/signalr";

        public IHubProxy Proxy { get; set; }
        public HubConnection Connection { get; set; }

        public bool Active { get; set; }

        public MainWindow()
        {
            InitializeComponent();
        }

        private async void ActionSendButtonClick(object sender, RoutedEventArgs e)
        {
            await SendMessage();
        }

        private async Task SendMessage()
        {
            await Proxy.Invoke("Addmessage", ClientNameTextBox.Text , MessageTextBox.Text);
        }
        private async void ActionWindowLoaded(object sender, RoutedEventArgs e)
        {
            Active = true;
            Thread = new System.Threading.Thread(() =>
            {
                Connection = new HubConnection(Host);
                Proxy = Connection.CreateHubProxy("MyHub");
                Proxy.On<string, string>("addmessage", (name, message) => OnSendData(name + ": " + message ));
                Connection.Start();

                while (Active)
                {
                    System.Threading.Thread.Sleep(10);
                }
            }) { IsBackground = true };
            Thread.Start();

        }

        private void OnSendData(string message)
        {
            try
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => MessagesListBox.Items.Insert(0, message)));
            }
            catch (Exception e)
            {
            }
        }

        private async void ActionMessageTextBoxOnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter || e.Key == Key.Return)
            {
                await SendMessage();
                MessageTextBox.Text = "";
            }
        }
    }

【问题讨论】:

    标签: .net asp.net-mvc deployment signalr signalr-hub


    【解决方案1】:

    您好,有几个答案,

    这是一个 MS 示例 https://code.msdn.microsoft.com/windowsdesktop/Using-SignalR-in-WinForms-f1ec847b

    这是另一个关于 wpf 的示例 http://damienbod.wordpress.com/2013/11/20/signalr-a-complete-wpf-client-using-mvvm/

    虽然第一个链接说的是 winforms,但它也涵盖了 wpf。

    万一链接断开,你想使用这个金块包 Microsoft.AspNet.SignalR.Client

    以上包支持 此软件包支持 .NET 4 和 .NET 4.5 的 WinRT、Silverlight、WPF、控制台应用程序和 Windows Phone 客户端。

    您可以在此链接中找到有关该 nugget 包的更多信息 http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-net-client

    public partial class MainWindow : Window
    {
        public System.Threading.Thread Thread { get; set; }
        public string Host = "http://x.x.x.x:8089/";
    
        public IHubProxy Proxy { get; set; }
        public HubConnection Connection { get; set; }
    
        public bool Active { get; set; }
    
    
        public MainWindow()
        {
            InitializeComponent();
        }
    
        private async void ActionHeartbeatButtonClick(object sender, RoutedEventArgs e)
        {
            await SendHeartbeat();
        }
    
        private async void ActionSendButtonClick(object sender, RoutedEventArgs e)
        {
            await SendMessage();
        }
    
        private async void ActionSendObjectButtonClick(object sender, RoutedEventArgs e)
        {
            await SendHelloObject();
        }
    
        private async Task SendMessage()
        {
            await Proxy.Invoke("Addmessage", ClientNameTextBox.Text, MessageTextBox.Text);
        }
    
        private async Task SendHeartbeat()
        {
            await Proxy.Invoke("Heartbeat");
        }
    
        private async Task SendHelloObject()
        {
            HelloModel hello = new HelloModel { Age = Convert.ToInt32(HelloTextBox.Text), Molly = HelloMollyTextBox.Text };
            await Proxy.Invoke("sendHelloObject", hello);
        }
    
        private async void ActionWindowLoaded(object sender, RoutedEventArgs e)
        {
            Active = true;
            Thread = new System.Threading.Thread(() =>
            {
                Connection = new HubConnection(Host);
                Proxy = Connection.CreateHubProxy("MyHub");
    
                Proxy.On<string, string>("addmessage", (name, message) => OnSendData("Recieved addMessage: " + name + ": " + message));
                Proxy.On("heartbeat", () => OnSendData("Recieved heartbeat"));
                Proxy.On<HelloModel>("sendHelloObject", hello => OnSendData("Recieved sendHelloObject " + hello.Molly + " " + hello.Age));
    
                Connection.Start();
    
                while (Active)
                {
                    System.Threading.Thread.Sleep(10);
                }
            }) { IsBackground = true };
            Thread.Start();
    
        }
    
        private void OnSendData(string message)
        {
            Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => MessagesListBox.Items.Insert(0, message)));
        }
    
        private async void ActionMessageTextBoxOnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter || e.Key == Key.Return)
            {
                await SendMessage();
                MessageTextBox.Text = "";
            }
        }
    
    }
    
    
    
    <Window x:Class="SignalRTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="ActionWindowLoaded"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition Width="Auto"
                              MinWidth="149" />
        </Grid.ColumnDefinitions>
    
        <Label Content="Message:"
               Grid.Column="0"
               Grid.Row="0"
               Margin="5" />
        <TextBox Width="Auto"
                 Grid.Column="1"
                 Grid.Row="0"
                 Margin="5,5,10,5"
                 x:Name="ClientNameTextBox" />
        <TextBox Width="Auto"
                 Grid.Column="2"
                 Grid.Row="0"
                 Margin="5,5,10,5"
                 x:Name="MessageTextBox"
                 KeyDown="ActionMessageTextBoxOnKeyDown" />
        <Button Content="AddMessage"
                Grid.Column="3"
                Grid.Row="0"
                Margin="17,5"
                x:Name="SendButton"
                Click="ActionSendButtonClick" />
    
        <Label Content="Heartbeat:"
               Grid.Column="0"
               Grid.Row="1"
               Margin="5" />
        <Button Content="Send Heartbeat"
                Grid.Column="3"
                Grid.Row="1"
                Margin="17,5"
                x:Name="HeartbeatButton"
                Click="ActionHeartbeatButtonClick" />
    
        <Label Content="Age, Molly:"
               Grid.Column="0"
               Grid.Row="2"
               Margin="5" />
        <TextBox Width="Auto"
                 Grid.Column="1"
                 Grid.Row="2"
                 Margin="5,5,10,5"
                 x:Name="HelloTextBox" />
        <TextBox Width="Auto"
                 Grid.Column="2"
                 Grid.Row="2"
                 Margin="5,5,10,5"
                 x:Name="HelloMollyTextBox"
                 KeyDown="ActionMessageTextBoxOnKeyDown" />
        <Button Content="Send Object"
                Grid.Column="3"
                Grid.Row="2"
                Margin="17,5"
                x:Name="HelloButton"
                Click="ActionSendObjectButtonClick" />
    
        <ListBox Grid.Column="0"
                 Grid.Row="3"
                 Grid.ColumnSpan="4"
                 Margin="5"
                 x:Name="MessagesListBox" />
    </Grid>
    

    public class HelloModel
    {
        public string Molly { get; set; }
    
        public int Age { get; set; }
    
    }
    

    【讨论】:

    • 我遵循了 MS 上的相同示例,问题是它在本地运行良好。但是,当我在远程服务器上运行作为主机工作的同一个控制台应用程序时,我的 wpf 应用程序无法与其连接。我想问题是它没有通过 tcp 连接,因为我的 Web 应用程序仍在连接到它。
    • 所以我想知道的是,如果有任何方法可以使用托管在远程服务器上的信号 r 连接到我在本地桌面上运行的应用程序。
    • 如果您的问题只是在部署到远程计算机时出现连接问题,则可能是多种原因,例如防火墙阻止了服务器上的请求,或者不太可能出现在客户端。也可能是客户端的dns问题,无法找到服务器的IP地址。您将需要确保在您的浏览器中输入您在客户端上用于信号器的 url 时,您能够从客户端获取,您至少可以返回错误消息,例如未知传输或其他东西沿着这些思路。
    • 从技术上讲,SignalR 可以在您的场景中工作,因为您已经在本地对其进行了测试并且知道您的代码可以正常工作。您很可能正在处理其他一些与网络相关的问题,例如我之前提到的那些。
    • 好的,我在聊天中等待,不能再等了。然而,在等待的时候,我确实编写了 wpf 客户端和控制台客户端。我的两个都按预期工作。所以我会说你的服务器端代码很好。
    猜你喜欢
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多