我有一个连接到信号中心的 Expo React 本机应用程序:
const connection = new signalR.HubConnectionBuilder()
.withUrl("http://server_where_hub_is_hosted:5000/stockHub")
.configureLogging(signalR.LogLevel.Information)
.withAutomaticReconnect()
.build();
如果我使用 expo go,或直接在浏览器上测试应用程序,它工作正常,它会按预期连接到信号中心。
但是,如果我使用“eas build -p android --profile Preview”构建应用程序 apk 并将其安装在我的手机上,它似乎无法连接到信号集线器。这是为什么?我可以通过其他设备/网络上的 url 连接到集线器,但使用 apk 时则不行。
我什至不确定问题是来自客户端还是服务器端。
这是我的信号器配置:
using WorkerService;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
internal class Program
{
private static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
builder.Services.AddHostedService<Worker>();
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
builder.Services.AddWindowsService(options =>
{
options.ServiceName = "ReadQueueService";
});
builder.Services.AddSingleton<ConnectDatabase>();
builder.WebHost.UseUrls("http://0.0.0.0:5000");
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<StockHub>("/stockHub");
});
app.Run();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
我尝试过指定来源、使用内部电话ip等方式但没有成功。
应该是最新的android默认不支持HTTP请求。
找到
AndroidManifest.xml
文件,然后启用 android:usesCleartextTraffic="true"
。
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>