首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SignalR无法用任何可用的传输从客户端连接到服务器

SignalR无法用任何可用的传输从客户端连接到服务器
EN

Stack Overflow用户
提问于 2022-11-17 10:51:17
回答 1查看 131关注 0票数 1

我正在尝试连接到我的服务器上用SignalR (.NET)建立的websocket。

我的客户端(JavaScript)启动协商,获得connectionId、connectionToken等的响应,但之后无法连接到任何可用的传输方法。

我得到的最后一个调试跟踪是:

[2022-11-17T10:21:02.093Z] Debug: HubConnection failed to start successfully because of error 'Error: Unable to connect to the server with any of the available transports. WebSockets failed: Error: There was an error with the transport. ServerSentEvents failed: Error: Error occurred LongPolling failed: Error'.

我的服务器代码:

Startup.cs

代码语言:javascript
复制
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace Sample
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0).AddNewtonsoftJson();
            services.AddSignalR().AddNewtonsoftJsonProtocol(opt => {
                opt.PayloadSerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.WithOrigins("http://localhost:8080", "http://127.0.0.1:8080")
                       .AllowAnyMethod()
                       .AllowAnyHeader()
                       .AllowCredentials();
            }));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseFileServer();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseCors("MyPolicy");
            app.UseMvc();
            app.UseRouting();
            app.UseEndpoints(routes =>
            {
                routes.MapHub<Controllers.DesignAutomationHub>("/api/signalr/designautomation");
            });

        }
    }
}

主计长:

代码语言:javascript
复制
using Autodesk.Forge;
using Autodesk.Forge.DesignAutomation;
using Autodesk.Forge.DesignAutomation.Model;
using Autodesk.Forge.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Sample.Controllers
{
    [ApiController]
    public class ServiceController : Controller
    {
        // Design Automation v3 API
        DesignAutomationClient _designAutomation;
        // Used to access the application folder (temp location for files & bundles)
        private IWebHostEnvironment _env;
        // used to access the SignalR Hub
        private IHubContext<DesignAutomationHub> _hubContext;

        public ServiceController(IWebHostEnvironment env, IHubContext<DesignAutomationHub> hubContext, DesignAutomationClient api)
        {
            _designAutomation = api;
            _env = env;
            _hubContext = hubContext;
        }
    }

    /// <summary>
    /// Class uses for SignalR
    /// </summary>
    public class DesignAutomationHub : Microsoft.AspNetCore.SignalR.Hub
    {
        public string GetConnectionId() { return Context.ConnectionId; }
    }
}

客户端:

代码语言:javascript
复制
var connection;
var connectionId;

function startConnection(onReady) {
  if (connection && connection.connectionState) {
    if (onReady) onReady();
    return;
  }
  connection = new signalR.HubConnectionBuilder()
    .withUrl(
      "http://<SERVERADRESS>/api/signalr/designautomation"
    )
    .configureLogging(signalR.LogLevel.Trace)
    .build();
  connection.start().then(function () {
    connection.invoke("getConnectionId").then(function (id) {
      connectionId = id; 
      if (onReady) onReady();
    });
  });

  connection.on("downloadResult", function (url) {
    console.log('<a href="' + url + '">Download result file here</a>');
  });

  connection.on("onComplete", function (message) {
    console.log(message);
  });
}

我在一台机器上用服务器和客户端对它进行了本地测试,一切正常。但是自从部署测试之后,我得到了错误。(在服务器上激活Websockets。)

此外,邮递员可以建立一个连接到websocket,只有我的客户失败。

任何帮助我都会感激的。提前感谢!

编辑:我还尝试通过(这里)描述的替代SignalR客户端连接到SignalR。

代码语言:javascript
复制
async function connectToWebsocket(negotiations) {
  let token = encodeURIComponent(negotiations.connectionToken);
  let wssPath = `ws://<SERVERADRESS>/api/signalr/designautomation?id=${token}`;
  let ws = new WebSocket(wssPath);

  console.log(ws);
}

async function connectToSignalR() {
  $.ajax({
    url: "<SERVERADRESS>/api/signalr/designautomation/negotiate?negotiateVersion=1",
    contentType: "application/json",
    dataType: "json",
    headers: { "Access-Control-Allow-Origin": "*" },
    type: "POST",
    success: function (res) {
      console.log(res);
      connectToWebsocket(res);
    },
    error: function (error) {
      console.log(error);
    },
  });
}

结果还是一样的。我从谈判中得到了回应,但无法连接到websocket。

作为补充信息。我的“服务器”是Azure-VM上的iis快车,带有via ngrok转发入口。

另一个编辑:--关于使用SignalR的整个例子是让一个websocket连接运行,当他们完成我提交的任务时,autodesk伪造服务器可以回调这个连接,以便让他们知道下一个任务是什么。我添加了标签,也许来自这个方向的人遇到了同样的问题,可以给出一个提示。

和另一个编辑:--我现在也用我能找到的最简单的例子--来自微软的聊天应用示例--尝试连接到远程服务器。还是同样的问题。我在这里添加了整个控制台输出:

我也很好奇我的警察是不是出了什么问题。但它被定义在每一个工作例子中.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-22 19:20:36

这个问题是由ngrok和可能是CORS造成的(如控制台输出中所述)。

在朝正确的方向推进后,我尝试了另一种工具(传送器- VS扩展)将本地主机转发到网络。从远程客户端连接到websocket或任何其他传输方法绝对没有问题。

因此,对于任何有同样问题的人,尝试调试用iis-express中的ngrok转发的websocket连接,并获得CORS错误,请使用传送器代替。只要您不知道如何配置ngroks CORS处理("http -host-header=rewrite“并没有起作用)。

如果您知道如何配置ngroks CORS处理,我很乐意在评论中阅读它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74474165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档