[英]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,这些是我遵循的步骤:
SignalRServer
, using Indentity for authentication.我使用名为SignalRServer
ASP.NET Web App 项目创建了一个新解决方案,使用SignalRServer
进行身份验证。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);
}
}
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
ConfigureAuth(app);
}
}
Server implementation is done.服务器实现完成。 After that, the client:之后,客户端:
SignalRClient
.我添加了一个名为SignalRClient
的新 WPF 项目。Microsoft.AspNet.SignalR.Client
package using Nuget.我使用 Nuget 添加Microsoft.AspNet.SignalR.Client
包。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>
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.