Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSocket is not in the OPEN state

I'm trying SignalR on ASP.NET Core. It works fine running from VisaulStudio debugger.

However it does not work in deployed code, showing the error message "WebSocket is not in the OPEN state" and "Handshake was canceled". What is the possible cause of the problem?

  • Microsoft.AspNetCore.Mvc 2.2.0
  • Microsoft.AspNetCore.SignalR 1.1.0
  • @aspnet/signalr 1.1.2
  • Bootstrap4
  • jQuery v3.1.0
  • Kestrel
  • No HTTPS SSL
  • Tried with Windows 7 and Ubuntu 18.4

Network Console on Google Chrome

WebSocket is not in the OPEN state (kms-event-exit.js:12)
Uncaught Error: Seerver returned handshake error: Handshake was canceled. (signalr.min.js:16)
 at HubConnection.processHandshakeResponse (signalr.min.js:16)
 at HubConnection.processIncomingData (signalr.min.js:16)
 at WebSocketTransport.HubConnection.connection.onreceive (signalr.min.js:16)
 at WebSocket.webSocket.onmessag (signalr.min.js:16)
[2019-04-06T01:06:41.965Z] Error: Connection disconnected with error 'Error: Server returned handshake error: Handshake was canceled.'. signalr.min.js:16
Uncaught (in promise) Server returned handshake error: Handshake was canceled. (signalr.min.js:16)

Startup functions.

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddRazorOptions(options => options.AllowRecompilingViewsOnFileChange = true);

        services.AddSignalR(options => options.EnableDetailedErrors = true);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDeveloperExceptionPage();
        if (!env.IsDevelopment())
        {
            //app.UseExceptionHandler("/Home/Main");
            app.UseHsts();
        }

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseSignalR(routes =>
        {
            routes.MapHub<Hubs.KmsHub>("/KmsHub");
            routes.MapHub<Hubs.AllResetHub>("/AllResetHub");
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "areaDefault",
                template: "{area:exists}/{controller=Home}/{action=Main}/{id?}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Main}/{id?}/{exit?}");
        });
    }

Logs

dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionDispatcher[4]
      Establishing new connection.
dbug: Microsoft.AspNetCore.SignalR.HubConnectionHandler[5]
      OnConnectedAsync started.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsTransport[1]
      Socket opened using Sub-Protocol: '(null)'.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/favicon.ico
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
      Sending file. Request path: '/favicon.ico'. Physical path: 'D:\K4\KMS\KMS\bin\Release\netcoreapp2.2\publish\wwwroot\favicon.ico'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 6.664ms 200 image/x-icon
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/lib/Popper/popper.min.js.map
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 3.4573ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/lib/bootstrap/dist/js/bootstrap.min.js.map
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/lib/signalr/dist/browser/signalr.min.js.map
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 2.3443ms 404
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
      Sending file. Request path: '/lib/bootstrap/dist/js/bootstrap.min.js.map'. Physical path: 'D:\K4\KMS\KMS\bin\Release\netcoreapp2.2\publish\wwwroot\lib\boo
tstrap\dist\js\bootstrap.min.js.map'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 114.858ms 200 text/plain
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/lib/bootstrap/dist/css/bootstrap.min.css.map
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
      Sending file. Request path: '/lib/bootstrap/dist/css/bootstrap.min.css.map'. Physical path: 'D:\K4\KMS\KMS\bin\Release\netcoreapp2.2\publish\wwwroot\lib\b
ootstrap\dist\css\bootstrap.min.css.map'
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 18.0356ms 200 text/plain
dbug: Microsoft.AspNetCore.SignalR.HubConnectionContext[2]
      Handshake was canceled.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsTransport[7]
      Waiting for the client to close the socket.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsTransport[2]
      Socket closed.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionManager[2]
      Removing connection 8K2CDgDs6jWXM7DPMWk_Dg from the list of connections.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 15047.5227ms 101

JavaScript code which caught the exception.

function kmsEventExit(url) {
    var exitButton = document.getElementById("exitButton");
    var connection = new signalR.HubConnectionBuilder().withUrl(url + "/KmsHub").build();

    //Disable send button until connection is established
    exitButton.disabled = true;

    //Wait until connection finishes.
    connection.start().then(function () {
        exitButton.disabled = false;
    }).catch(function (err) {
        return console.error(err.toString());   //WebSocket is not in the OPEN state
    });

    //Call ExitKms on clicking the button.
    exitButton.addEventListener("click", function (event) {
        connection.invoke("ExitKms").catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });

    //Catch the result.
    connection.on("ExitKmsResult", function (isAlert, options) {
        if (isAlert) {
            swal(JSON.parse(options));
        }
    });
}
like image 312
Katsutoshi Hayashida Avatar asked Apr 06 '19 01:04

Katsutoshi Hayashida


People also ask

How do you check if WebSocket is open or not?

In the search field, enter websocket . From the search results, click WebSocket Connection Status.

How do I fix WebSocket connection error?

Solution 1Check that all the Bot Insight services are running. Check that your firewall settings are configured to accept incoming websocket data. Try to use a different web browser. Restart the Bot Insight Visualization and Bot Insight Scheduler services.

Why WebSocket is closed?

The WebSocket is closed before the connection is established error message indicates that some client code, or other mechanism, has closed the websocket connection before the connection was fully established.

Can WebSocket be stateless?

This is because opening a webSocket starts with an HTTP request/response and then after both sides have agreed to upgrade to a webSocket connection, the actual webSocket message can be sent. Stateless.


2 Answers

From the same URL provided by OP on his response, there has been an update to the issue which has worked for me (workaround).

Before connecting, add:

Object.defineProperty(WebSocket, 'OPEN', { value: 1, });

Credits to: https://github.com/aspnet/SignalR/issues/2389#issuecomment-393760284

This way, I didn't have to remove pace.js.

like image 72
Lucca Ferri Avatar answered Oct 20 '22 16:10

Lucca Ferri


I have identified the problem!

It did not work because pace.js was not compatible with signalr.js. WebSocket variable was duplicated in these two plugins. SignalR works fine after removing pace.js.

SignalR on VisualStudio worked with pace.js because it uses SSE and IIS Express, instead of WebSocket and Kestrel, thus pace.js and signalr.js can be compatible with this particular configuration.

Reference: https://github.com/aspnet/SignalR/issues/2389

like image 34
Katsutoshi Hayashida Avatar answered Oct 20 '22 16:10

Katsutoshi Hayashida