你好,我最近遇到了一些SignalR和Xamarin的麻烦。我使用Asp.net核心web应用程序和使用SignalR客户端包的xamarin表单。每当我试图连接时,我总是会得到错误的“连接拒绝”,我已经将我的代码与其他教程进行了比较,我相信它们是匹配的,但我仍然理解这个问题。这是我的代码:
Xamarin客户端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Neighbor_Mobile.SubPages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class GroupPage : ContentPage
{
HubConnection connection;
public GroupPage()
{
InitializeComponent();
AttemptConnect();
}
private async void AttemptConnect()
{
try
{
connection = new HubConnectionBuilder()
.WithUrl("https://localhost:44353/chat")
.Build();
connection.On<string>("ReceiveMessage", (message) => Display.Text = message);
await SignalRConnect();
}
catch (Exception e)
{
error.Text = $"error: {e}";
}
}
private async Task SignalRConnect()
{
try
{
//the error occurs here and prints "Connection Refused" to a debug label i'm using
await connection.StartAsync();
}
catch (Exception ex)
{
Display.Text = ex.Message;
return;
}
}
}
}这里是服务器上的启动页面代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FleetSocketServer.Hubs;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace FleetSocketServer
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<SocketGroupHub>("/chat");
});
}
}
}我的集线器页面代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace FleetSocketServer.Hubs
{
public class SocketGroupHub :Hub
{
public async Task SendMessage(string message)
{
await Clients.All.SendAsync("Recieve", message);
}
}
} 我的launchSettings我尝试用iisSettigns和FleetSocketServer调试它,同时在WithURL中更改URl,但仍然给出了相同的错误
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:35579",
"sslPort": 44353
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"FleetSocketServer": {
"commandName": "Project",
"launchBrowser": false,
"applicationUrl": "https://localhost:5001;http://localhost:5050",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}谢谢!
发布于 2021-08-30 07:03:27
好吧,我真的很傻,因为andriod模拟器使用10.0.2.2作为本地主机,而不是127.0.0.1,原因很明显。
https://stackoverflow.com/questions/68973421
复制相似问题