.NET Maui SignalR安卓真机连接异常求助:连接重置/HttpRequestException
.NET Maui SignalR安卓真机连接问题解决方案
问题描述
使用.NET Maui结合SignalR开发的聊天应用,在模拟器及Windows设备上运行正常,但安卓真机连接时出现以下问题:
- 初始配置下触发
System.Net.WebException: 'Connection reset'错误 - 改为
127.0.0.1后出现System.Net.Http.HttpRequestException错误
核心原因
安卓真机无法识别模拟器专属的10.0.2.2回环地址,也无法直接访问开发机的localhost,必须使用开发机在局域网内的实际IP地址,同时确保SignalR服务绑定到局域网可访问的IP。
修复步骤
1. 修改客户端连接地址
将安卓平台的baseUrl替换为开发机的局域网IP(需根据你的网络环境修改):
using Microsoft.AspNetCore.SignalR.Client; using Microsoft.Maui.Devices; namespace SignalRClient { public partial class MainPage : ContentPage { private readonly HubConnection hubConnection; public MainPage() { InitializeComponent(); var baseUrl = "http://localhost"; // 替换为你的开发机局域网IP,例如http://192.168.1.100 if (DeviceInfo.Current.Platform == DevicePlatform.Android) { baseUrl = "http://192.168.1.100"; } hubConnection = new HubConnectionBuilder() .WithUrl($"{baseUrl}:5127/chatHub") .Build(); hubConnection.On<string, string>("ReceiveMessage", (user, message) => { Dispatcher.Dispatch(() => { lblChat.Text += $"<b>{user}</b>: {message}<br/>"; }); }); } // 优化连接时机,移至生命周期方法并添加异常处理 protected override async void OnAppearing() { base.OnAppearing(); try { if (hubConnection.State == HubConnectionState.Disconnected) { await hubConnection.StartAsync(); } } catch (Exception ex) { lblChat.Text += $"连接失败: {ex.Message}<br/>"; } } private async void btnSend_Clicked(object sender, EventArgs e) { await hubConnection.InvokeCoreAsync("SendMessageToAll", args: new[] { txtUsername.Text, txtMessage.Text }); txtMessage.Text = String.Empty; } } }
2. 配置SignalR服务器绑定局域网IP
修改服务器的launchSettings.json,将applicationUrl设置为绑定所有可用IP,确保安卓真机可访问:
{ "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:28341", "sslPort": 44341 } }, "profiles": { "SignalRServer": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "applicationUrl": "https://0.0.0.0:7127;http://0.0.0.0:5127", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.Azure.SignalR" } }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.Azure.SignalR" } } } }
3. 检查防火墙设置
确保开发机防火墙允许5127(HTTP)和7127(HTTPS)端口的入站连接,否则安卓真机无法建立连接。
4. 验证网络连通性
在安卓真机浏览器中访问http://你的开发机IP:5127/chatHub,若返回Connection ID required页面,说明服务已可达。
生产环境注意事项
- 将
AndroidManifest.xml中的android:usesCleartextTraffic="true"改为false,使用HTTPS连接保障数据安全。 - 建议使用配置文件管理服务地址,避免硬编码。
内容的提问来源于stack exchange,提问作者begums
相关产品推荐
相关产品推荐

