SignalR server closes connection immediately when the client connects

1

I want to use SignalR in a project to send reboot messages to devices, but I can not. 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

I am using Visual Studio Professional 2017 with .NET 4.7.2, and these are the steps I followed:

  1. I create a new solution with ASP.NET Web App project named SignalRServer, using Indentity for authentication.
  2. I create new folder named SignalR and add new item > SignalR Hub Class (v2). I named it 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:
    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.
  2. I add Microsoft.AspNet.SignalR.Client package using Nuget.
  3. I change 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:
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). 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?

c#
asp.net
.net
signalr
asked on Stack Overflow Mar 6, 2020 by Jon

1 Answer

1

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.

You may consider removing using statement and saving hubConnection as a field or property to call hubConnection.Stop() later to disconnect.

answered on Stack Overflow May 20, 2020 by Dmitry Vasilevich

User contributions licensed under CC BY-SA 3.0