简体   繁体   English

SignalR 服务器在客户端连接时立即关闭连接

[英]SignalR server closes connection immediately when the client connects

I want to use SignalR in a project to send reboot messages to devices, but I can not.我想在项目中使用 SignalR 向设备发送重启消息,但我不能。 So I decided to start a new solution only for testing purposes with the same results:所以我决定开始一个新的解决方案,仅用于测试目的,结果相同:

SocketException (0x80004005): An existing connection was forcibly closed by the remote host SocketException (0x80004005): 现有连接被远程主机强行关闭

I am using Visual Studio Professional 2017 with .NET 4.7.2, and these are the steps I followed:我正在使用带有 .NET 4.7.2 的 Visual Studio Professional 2017,这些是我遵循的步骤:

  1. I create a new solution with ASP.NET Web App project named SignalRServer , using Indentity for authentication.我使用名为SignalRServer ASP.NET Web App 项目创建了一个新解决方案,使用SignalRServer进行身份验证。
  2. I create new folder named SignalR and add new item > SignalR Hub Class (v2).我创建名为SignalR新文件夹并添加新项目 > SignalR Hub Class (v2)。 I named it SignalRHub :我将它命名为SignalRHub
public class SignalRHub : Hub
{
    public void Reboot()
    {
        Clients.All.reboot();
    }
    public void Hello()
    {
        Clients.All.hello();
    }
    public override Task OnConnected()
    {
        Debug.WriteLine($"[SERVER] {this.Context.ConnectionId} connected");
        return base.OnConnected();
    }
    public override Task OnReconnected()
    {
        Debug.WriteLine($"[SERVER] {this.Context.ConnectionId} reconnected");
        return base.OnReconnected();
    }
    public override Task OnDisconnected(bool stopCalled)
    {
        Debug.WriteLine($"[SERVER] {this.Context.ConnectionId} disconnected");
        return base.OnDisconnected(stopCalled);
    }
}
  1. In Startup.cs file:在 Startup.cs 文件中:
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
            ConfigureAuth(app);
        }
    }

Server implementation is done.服务器实现完成。 After that, the client:之后,客户端:

  1. I add a new WPF project named SignalRClient .我添加了一个名为SignalRClient的新 WPF 项目。
  2. I add Microsoft.AspNet.SignalR.Client package using Nuget.我使用 Nuget 添加Microsoft.AspNet.SignalR.Client包。
  3. I change MainWindow.xaml :我改变MainWindow.xaml
<Window x:Class="SignalRClient.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:SignalRClient"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="400" Loaded="Window_Loaded">
    <Grid>
        <Button VerticalAlignment="Center" HorizontalAlignment="Center" Padding="5" Content="Send message!" Click="Button_Click"/>
    </Grid>
</Window>
  1. And finally I change MainWindow.xaml.cs :最后我更改MainWindow.xaml.cs
public partial class MainWindow : Window
{
    private IHubProxy signalRHubProxy;

    public MainWindow()
    {
        InitializeComponent();
    }

    private async void Window_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            using (var hubConnection = new HubConnection("http://localhost:54475/"))
            {
                this.signalRHubProxy = hubConnection.CreateHubProxy("SignalRHub");
                this.signalRHubProxy.On("Hello", this.HelloMessageReceived);
                this.signalRHubProxy.On("Reboot", this.RebootMessageReceived);
                ServicePointManager.DefaultConnectionLimit = 10;
                await hubConnection.Start();
                Debug.WriteLine($"[CLIENT] Connected to hub");
            }
        }
        catch (Exception exception)
        {
            Debug.WriteLine($"[CLIENT] {exception.Message}");
        }
    }

    private void HelloMessageReceived()
    {
        Console.WriteLine("[CLIENT] Hello message received");
    }
    private void RebootMessageReceived()
    {
        Console.WriteLine("[CLIENT] Reboot message received");
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        await this.signalRHubProxy.Invoke("Hello", new { });
    }
}

The client is done too.客户端也完成了。 Now I run the web app first, and when the home page is loaded I run the WPF app (Debug > Start new instance).现在我首先运行 Web 应用程序,当加载主页时,我运行 WPF 应用程序(调试 > 启动新实例)。 This is the output:这是输出:

[SERVER] b3f11c77-6bfc-416a-914b-f2573f0cc42c connected
[CLIENT] Connected to hub
[SERVER] b3f11c77-6bfc-416a-914b-f2573f0cc42c disconnected
SignalRClient.exe Error: 0 : Error while closing the websocket: System.Net.WebSockets.WebSocketException (0x80004005): An internal WebSocket error occurred. Please see the innerException, if present, for more details.  ---> System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
   at System.Net.WebSockets.WebSocketConnectionStream.WebSocketConnection.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.DelegatedStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketConnectionStream.<>n__1(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketConnectionStream.<WriteAsync>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<SendFrameAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Net.WebSockets.WebSocketBase.WebSocketOperation.<Process>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__51.MoveNext()
   at System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(String methodName, Exception exception, CancellationToken cancellationToken, Boolean aborted)
   at System.Net.WebSockets.WebSocketBase.<CloseOutputAsyncCore>d__51.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.WebSockets.WebSocketHandler.<>c.<<CloseAsync>b__13_0>d.MoveNext() in /_/src/Microsoft.AspNet.SignalR.Core/Owin/WebSockets/WebSocketHandler.cs:line 114
The thread 0x4b44 has exited with code 0 (0x0).
The thread 0x5560 has exited with code 0 (0x0).

I can see that the client connects to the server, but the connection is immediately closed.我可以看到客户端连接到服务器,但连接立即关闭。 I don't know if I am forgetting a step.我不知道我是不是忘记了一步。 I stopped the firewall with the same result.我以相同的结果停止了防火墙。 Do you know how can I solve the problem?你知道我该如何解决这个问题吗?

It seems like using statement is the reason as it disposes created HubConnection object at the end of try block which leads to websocket closing.似乎using语句是原因,因为它在try块的末尾处理创建的HubConnection对象,这导致 websocket 关闭。

You may consider removing using statement and saving hubConnection as a field or property to call hubConnection.Stop() later to disconnect.您可以考虑删除using语句并将hubConnection保存为字段或属性,以便稍后调用hubConnection.Stop()以断开连接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 客户端关闭连接时在服务器上多次调用NetworkStream回调 - NetworkStream callback called multiple times on server when client closes connection 尝试使用connection.Start()连接到服务器时出现SignalR Client错误 - SignalR Client error when trying to connect to server with connection.Start() SignalR:服务器如何建立与客户端的连接? - SignalR: how Server can establish connection to Client? SignalR 客户端-服务器连接问题 - SignalR client-server connection issue 服务器关闭保持活动状态的HTTP连接时检测或避免客户端CommunicationException - detecting or avoiding client CommunicationException when server closes keep-alive http connection 尝试将数据写入客户端时,C#中的简单套接字服务器意外关闭连接 - Simple socket server in C# unexpectedly closes connection when trying to write data to client 服务器在发送后立即关闭时从NetworkStream读取数据 - Reading data from NetworkStream when server closes immediately after sending 当我尝试使用SignalR建立客户端和服务器连接时出错 - Error when I am trying to establishing a client and server connection using SignalR SignalR - 客户端连接在启动后立即关闭 - InvalidOperationException:序列不包含任何元素 - SignalR - Client connection closes straight after starting - InvalidOperationException: Sequence contains no elements C#套接字:客户端连接时获取服务器 - c# socket: get server when client connects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM