GithubHelp home page GithubHelp logo

azuresignalr-samples's People

Contributors

chenkennt avatar chhtw avatar dependabot[bot] avatar diberry avatar digidol avatar divanvanzyl avatar hobpet avatar jialinxin avatar lgdoor avatar lizh-lixiang avatar mburleigh avatar microsoftopensource avatar msftgits avatar mwittenbols avatar onionhammer avatar sanjaysingh avatar sjwaight avatar terencefan avatar terrajobst avatar ubikusss avatar vavjeeva avatar vicancy avatar vwxyzh avatar vyunev avatar wanlwanl avatar xingsy97 avatar xscript avatar y-sindo avatar zackliu avatar zhiliangxu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

azuresignalr-samples's Issues

No executable found matching command "dotnet-user-secrets"

In chat room sample I was experiencing No executable found matching command "dotnet-user-secrets" error, when trying to add Azure SignalR Service connection string to user-secrets. It was necessary to add following code to csproj file.

  <ItemGroup>
	<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0-msbuild3-final" />
  </ItemGroup>

Issue in Advanced Chat Room Sample

When you try to create / join a new group with a message, this event is called in ChatBase.cs:
NOTE: Same issue occurs in ChatBase.cs --> LeaveGroup.

public async void JoinGroup(string name, string groupName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("echo", "SYSTEM", $"{name} joined {groupName} with connectionId {Context.ConnectionId}");
}

The first line executes fine --> "await Groups.AdToGroupAsync...."
Upon executing the second line --. This exception is thrown:

System.ObjectDisposedException: 'Cannot access a disposed object.
Object name: 'ChatJwtSampleHub'.'

If I simply remove the second line of code "await Clients.Group..." from the method, it executes fine, the group is created, and I can send messages to the group.

Still, it's odd that the object is disposed after the first line of code "Groups.AddToGroup". It seems you should be able to call "await Clients.Group..." per the sample without hitting the exception.

Not getting hub OnConnected/OnDisconnectedAsync calls

I switched from SignalR (AspNetCore RC1) to AzureSignalR
I use authenticated hubs (using JWT Bearer tokens in header)
When a client connects, I add the connection to a group for its Tenant (a multitenant solution, tenant is a claim in the JWT).
However - in the AzureSignalR version, my hub does not get these events.

My code defines
public override async Task OnConnectedAsync()

I noticed the sample code in FlightMap does not use async,
public override Task OnConnectedAsync()

Changing my code to use this signature still doesnt work.

Found the angular client was requesting HttpTransportType.WebSockets. When removing that ... it works!

ARM Creation of Azure Signalr Service

Hello,

Aside from using Azure CLI or creating via Azure Portal;

is there any Powershell command or ARM way of creating the new Azure Signalr Service .

thank you.

HubCallerContext.GetHttpContext returns null

Expected Behavior
When using (non-Azure) SignalR for ASP.NET Core, my hub's OnConnectedAsync method was using Context.GetHttpContext() to get the HTTP context for the SignalR connection in order to view query strings from the client's connection request (and made client grouping decisions based on that data).

Actual Behavior
Using Azure SignalR as a Service, my hub receives OnConnectedAsync calls as expected, but Context.GetHttpContext() returns null.

More Details

Client code creating the SignalR connection:

var connection = new signalR.HubConnectionBuilder()
    .withUrl(connectionUrl + '?gameId=' + gameId)
    .build();

Resulting calls using (non-Azure) SignalR:

OPTIONS http://localhost:5002/game/negotiate?gameId=M1pdnjc5
POST http://localhost:5002/game/negotiate?gameId=M1pdnjc5
GET http://localhost:5002/game?gameId=M1pdnjc5&id=f6pYCEmiObwaStHE0T2e9w

Resulting calls using ASRS:

OPTIONS http://localhost:5002/game/negotiate?gameId=6ljoK2lS
POST http://localhost:5002/game/negotiate?gameId=6ljoK2lS
OPTIONS https://mikerou-chat.service.signalr.net:5001/client/negotiate?hub=gamehub
POST https://mikerou-chat.service.signalr.net:5001/client/negotiate?hub=gamehub
GET https://mikerou-chat.service.signalr.net:5001/client/?hub=gamehub&id=aSnwi0uP6EJrbo9AW2CG8w&access_token=<JwtToken>

Data Generation

In the FlightPlan sample, it is unclear to me how to generate the flight data and/or derive the "DataFileUrl". There seems to be a js file in the data folder, but the readme also refers to azure blob storage. I'm sure I'm missing something.

Work with AspNetCore 2.1 preview 2 final?

When tried with AspNetCore 2.1 preview 2, got the error below when calling services.AddAzureSignalR()

System.TypeLoadException
HResult=0x80131522
Message=Could not load type 'Microsoft.AspNetCore.SignalR.Internal.Protocol.ProtocolType' from assembly 'Microsoft.AspNetCore.SignalR.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
Source=Microsoft.Azure.SignalR
StackTrace:
at Microsoft.Extensions.DependencyInjection.AzureSignalRDependencyInjectionExtensions.AddAzureSignalR(IServiceCollection services, Action`1 configure)
at EzPort.WebAPI.Startup.ConfigureServices(IServiceCollection services)

Any help?

Thanks!

"No server available" after scale down

When I use Azure SignalR Service and scale out my backend everything works as expected and my clients are distributed among the backends. When I scale down (decrease the number of replicas) I start getting No server available on the clients i.e. {"type":7,"error":"No server available."} on the WebSocket connection after first attempt to invoke hub method. The problem occurs only for some clients. If I rescale to previous number of replicas everything starts to work correctly.

Given the scaled out number of replicas is 10 and scaled down is 1 the problem is quite severe i.e. I get the error most of the time.

The issue can be reproduced with following docker-compose.yml. localhost:5000/chatroom is the image of the sample chatroom build into container using the provided Dockerfile.

version: '3'

services:
  backend: 
    image: localhost:5000/chatroom
  proxy:
    image: dockercloud/haproxy
    depends_on:
      - backend
    links:
      - backend
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    ports:
      - 80:80

Repro steps:

  1. Run docker-compose up --scale backend=10
  2. Connect some clients.
  3. Run docker-compose up --scale backend=1

This compose file will run multiple instances of the chat sample and a HAProxy in front for load balancing. The dockercloud version of HAProxy will auto configure to forward to all containers in the same compose file.

Unable to connect with azure siganlr service

I follow this github: https://github.com/Azure-Samples/signalr-service-quickstart-serverless-chat

After updated the Microsoft.Azure.WebJobs.Extensions.SignalRService to 1.0.0-preview1-10025, then my connection will close instantly after connect.

I worked with:
Microsoft.Azure.WebJobs.Extensions.SignalRService: 1.0.0-preview1-10002
Microsoft.AspNetCore.SignalR.Client: 1.1.0

but now the azure signalr is no longer support 1.0.0-preview1-10002.

I updated 10025, then signalR client will always close the connection said
{Microsoft.AspNetCore.SignalR.HubException: The server closed the connection with the following error: No app server is currently connected to the Azure service.}

Microsoft.Azure.WebJobs.Extensions.SignalRService: 1.0.0-preview1-10025
Microsoft.AspNetCore.SignalR.Client: 1.1.0

Don't know which combination is match... sad

Please add a sample for Unity3d

The SignalR backend is super useful, but is hard to use from Unity because of the different plugin & runtime requirements.

Failing to connect using the client app: Management SDK Example

Apologies if it's a duplicate issue.

I'm trying to run the Azure SignalR Service Management SDK Sample but the client app fails with this exception:

Microsoft.AspNetCore.SignalR.HubException: Unable to complete handshake with the server due to an error: SignalR Service is now in 'Default' service mode. Current mode works as a proxy that routes client traffic to the connected app servers. However app servers are not connected.

Any idea as to what causes this exception?

Thanks

Question about SignalR Example with CORS

I need to connect to the Azure SignalR Hub as a client from JavaScript - outside of the ASPCore.NET WebServer project. this means my JavaScript runs in a different Website - hosted by another system.

Is this possible? If yes, please provide some Information / example code for:

  • connect to the Hub & Subscribe a channel / Which URL should be used
  • Setup the Bearer-Token in JavaScript
  • Which script can I include in my HTML?
  • how can I configure the CORS on the Hub to secure my calls

My current approaches for connect to the Hub as HTML

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <!--Reference the SignalR library. -->
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@aspnet/[email protected]/dist/browser/signalr.min.js"></script>

        <!-- Another approach -->
        <script src="script/jquery-1.6.4.min.js"></script>
        <script src="script/jquery.signalR-2.2.2.min.js"></script>

        <script type="text/javascript">

            function initializeHub()
            {
                try {
                    // My Azure SignalR service information: 
                    const endpoint = 'https://MYSIGNALRSERVER.azurewebsites.net';
                    const key      = 'AAAAZZZZZZZZZZZZZZZZZZDDDDDDDDDDDD=';
                    const hubName  = 'chat';
                    
                    // Azure SignalR don't work :(
                    // --------------------------------------------------------------
                    // - How can I specify the base URL of the Azure SignalR Service?
                    // - How can I add the Authentication Key
                    // var connection = new signalR.HubConnectionBuilder()
                    //                            .withUrl('/' + hubName)
                    //                            .build();
                    // Subscribe for broadcastMessage(string)
                    // connection.on('broadcastMessage', function (message) {
                    //     try {
                    //         console.log("Message received: " + message);
                    //     } catch (error) {
                    //         console.error(error)
                    //     }            
                    // });


                    // Another approach - don't work too :( 
                    // --------------------------------------------------------------
                    // - How can I add the Authentication Key / Setup the Baerer 
                    // - Where should I specify the channel 'chat'
                    var connection       = $.hubConnection();
                    connection.url       = endpoint + ':5001/client/?hub=' + hubName;
                    hubProxy             = connection.createHubProxy(hubName);

                    // Subscribe for broadcastMessage(string)
                    hubProxy.on('broadcastMessage', function (message) {
                        try {
                            console.log("Message received: " + message);
                        } catch (error) {
                            console.error(error)
                        }            
                    });

                    // Connect to the Hub
                    connection
                        .start( { transport: 'longPolling' } )
                        .done(function () { console.log("Hub connected."); })
                        .fail(function (error) { console.error("initialize Hub failed: " + error); });

                } catch (error) {
                    console.error("initialize Hub failed: " + error);
                }
            };

            $(function () { 
                console.log('init the Hub ...');
            
                initializeHub();                
            });

        </script>
    </body>
</html>
```

Hope someone can help.

Issue when scaling out aspnetcore API with Azure Signal R service

See diagram

I have a multi tenant aspnet core solution, using Azure SignalR as a service.
There are 2 instances of the aspnetcore API. Each has a hub
When the user logs in to the API it gets a JWT with claims for user id, tenant id and session id (a unique GUID for each session).
The signalr connection uses this same JWT.
When a user connects (signalr), I know throught the claims who they are, and I add the connection to three groups, one for the user (by userid), one for the tenant (by tenantid), and one for the session (by session guid).
When they disconnect I remove them from all three groups
Now I can send messages to the user, to the session and to the tenant.

Here the problem:

This works fine if I just have one instance of the API.
But if I scale out to 2, and one of the instances sends a message, sometimes it goes to the client, sometimes not.

I was under the impression that with SignalR as a service, the groups created and the connection/disonnection events where replicated between all hub instances, as they are when using say a Service Bus or SQL backplane for regular non Azure signalR. But that doesn't seem to be the case?

If I am right, can I not use Azure SignalR Service - do I need to revert back to using embeded SignalR with my own backplane?

image

Wrong Pricing

The ChatRoom samples says:
Free: which can handle 100 connections at the same time and can send and receive one million messages in a month.
Basic: which has 1000 concurrent connections and 75 millions message per month limit for one unit. You can scale up to 10 units for a single service instance and you'll be charged by the number of units you use.

Per https://azure.microsoft.com/en-us/pricing/details/signalr-service/
Fee is only 20 concurrent connections
Concurrent Connections per Unit | 20
Messages / Unit / Day | 20,000
and Standard/Basic only allows:
Concurrent Connections per Unit | 1,000
Messages / Unit / Day | 1,000,000

Core and AspNet samples not talking together

I hope I'm missing something obvious, but I can't get the Core ChatRoom and AspNet ChatRoom samples to communicate together.

Apart from the different frameworks, all else seems equal. I've made a change in the Core sample to map the hub name to "chathub" to match the hub name from the AspNet sample.

Both samples seems to be connected to the same Azure SignalR service using the same connection string and key and both get a connection. The Core sample is running on localhost:5000 and the AspNet sample is running on localhost:63025 and both are talking to a hub named 'chathub'.

There are no errors in either browser console. The alternate samples are working independently in different browsers. Also, I see both are hitting Azure SignalR with connections and messages.

AdvancedChatRoom slower than ChatRoom

Just an observation - I have built both the ChatRoom as well as the AdvancedChatRoom and the performance difference between the two is very noticeable.

When sending a message from the ChatRoom example - it seems almost instantaneous that the message is shown in the chat window whereas with the AdvancedChatRoom example there seems to be a bit of a delay between pressing Broadcast and the message being displayed.

Any reason this is happening?

Thanks in advance.

Your Documentation For Your ChatRoom example is confusing

You need a 'For Dummies' version of your Read Me file.

I read this, and you don't show an example of what 'Your Application Name' should be.

You also say 'Set Your ConnectionString', but do not show an example.

In Startup.cs, instead of calling MapSignalR(), you need to call MapAzureSignalR({your_applicationName}) and pass in connection string to make the application connect to the service instead of hosting SignalR by itself. Replace {**YourApplicationName**} to the name of your application, this is the unique name to distinguish this application with your other application. You can use this.GetType().FullName as the value.

```cs
public void Configuration(IAppBuilder app)
{
    // Any connection or hub wire up and configuration should go here
    app.MapAzureSignalR(this.GetType().FullName);
}

On my first Azure Service I created, I have Host Name and ConnectionString.

Do I enter Host Name for Application Name?

An Example is worth 100 pages of documentation to me.

Thank you for telling me what to put, since your documentation forced me to close down the app.

AzureSignalR connection correct, but not notifying

Hey Guys,

I have a smal problem after publishing my web app on azure and consuming AzureSignalR.
After starting app, connection is working well and I can join groups. But if I push a Notification from my app like

 await hubContext.Clients.Groups(arbeitssystem.ShortId).SendAsync("StateChanged", arbeitssystem.ShortId);

groups were not notifyed.

#setup.cs ConfigureServices

            services.AddSignalR().AddHubOptions<Hubs.TwinHub>(options =>
            {
                options.EnableDetailedErrors = true;
            }).AddAzureSignalR();
app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapRazorPages();
                endpoints.MapHub<Hubs.TwinHub>("/TwinHubDashboard");
                endpoints.MapControllerRoute("api", "api/{controller}/{action}");
            });

But without .AddAzureSignalR(), so as local service, everything is working. Also after publishing on azure.
Any ideas whats going wrong?

Consider adding error handling to the samples

Currently we have something like:

public async Task MyRestCallHandler{
var result = await CalcResult();
await hub.Clients.SendAsync(...);
return result;
}

And if I don't wrap call to the hub into try-catch, the client gets 500 error, although the operation was generally ok. Sometimes client is an automated test which fails and gives a false alarm. All samples I find do not care for exceptions handling when contacting signalr.

How to put configuration for primary and secondary connection string in AppSettings ?

Hello,
I want to use multiple instances of azure signalr

In this documentation
https://docs.microsoft.com/en-us/azure/azure-signalr/signalr-concept-disaster-recovery

it says

Through config
You should already know how to set SignalR service connection string through environment variables/app settings/web.cofig, in a config entry named Azure:SignalR:ConnectionString. If you have multiple endpoints, you can set them in multiple config entries, each in the following format:

Copy
Azure:SignalR:ConnectionString::

but i want the same thing but in appsetting format
now i am using this with only one connection and it works
"Azure": {
"SignalR": {
"ConnectionString": ""
}
}

Thanks for help

Usage: send user <userId>, send group <groupName>, broadcast

Server is ran as:
C:\temp\AzureSignalR-samples\samples\Serverless> dotnet run -- server -c "Endpoint=https://test2-vncloud.service.signalr.net;AccessKey=xxx;Version=1.0;" -h chat

Client is ran as:
C:\temp\AzureSignalR-samples\samples\Serverless>dotnet run -- client client1 -c "Endpoint=https://test2-vncloud.service.signalr.net;AccessKey=xxx;Version=1.0;" -h chat

Usages I got to work:

broadcast
send user client1

What I couldn't got to work:
send group groupname

what groupname should I use to get the example (AzureSignalR-samples/samples/Serverless/) working?

Access Token Javascript Client

In the README is to be read:

This sample have been deprecated. Users are not recommended to generate access token by themselves. In the Serverless scenario, users are recommended to use Management SDK to build a negotiation server which is responsible for generating access token. For more samples and details, take Management Sample as reference.

What possibility is there to generate this access key on the client side?

[Question] [Serverless] How can I send a message to an individual client using REST API?

Dear Sirs,

I have studied the examples and I fully understand the architecture of Azure SignalR. I was able to broadcast messages from Postman. Also, I was able to run a chat example and was able to exchange messages.

The issue is: in a serverless scenario, how would I identify the id of an individual connected user? How Javascript clients can obtain their ID on Azure SignalR Service? This is needed because I want to send individual messages to a given user when his/her command gets processed on the backend. For example, in my use case, I would use a Azure Function to process a command that can take minutes to be executed.

What I have tried:

Using trace log on javascript client side, I was able to find an ID during negotiation:

Information: SSE connected to https://accendis-wefinance.service.signalr.net:5001/client/?hub=chat&id=61Ztvpa0KEQeKkJBgB2ZPQ&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE1MzEzNTY4OTcsImV4cCI6MTUzMTM1ODY5NywiaWF0IjoxNTMxMzU2ODk3LCJhdWQiOiJodHRwczovL2FjY2VuZGlzLXdlZmluYW5jZS5zZXJ2aWNlLnNpZ25hbHIubmV0OjUwMDEvY2xpZW50Lz9odWI9Y2hhdCJ9.NBFYcQaq-pl3c31AAeKmrLBIGnw-uON_MNWY0yMvJ_Y Utils.ts:165:20

So then I tried to build a new request using the id like this:

POST /api/v1-preview/hub/chat/user/61Ztvpa0KEQeKkJBgB2ZPQ HTTP/1.1
Host: accendis-wefinance.service.signalr.net:5002
Content-Type: application/json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1MzEzMTgyMTUsImV4cCI6MTU2Mjg1OTQ5NCwiYXVkIjoiaHR0cHM6Ly9hY2NlbmRpcy13ZWZpbmFuY2Uuc2VydmljZS5zaWduYWxyLm5ldDo1MDAyL2FwaS92MS1wcmV2aWV3L2h1Yi9jaGF0L3VzZXIvNjFadHZwYTBLRVFlS2tKQmdCMlpQUSIsInN1YiI6IiJ9.aVhw0AyQ-WuT9NIymFzESn6Gv3R3zLedddqCngLzxFg
Cache-Control: no-cache
Postman-Token: 329b9cbd-8f86-4e62-8a3f-c5e23b8af025

{ "target": "newMessage0", "arguments": [ {
	"sender": "mario",
	"text": "API rest do SignalR"
} ] }

And as result, I receive a 202 but nothing happens on client side.

How can I see what really happened?

How about a Xamarin Forms sample?

How about a Xamarin Forms sample, that covers following things
Creating Channel
Adding User
Removing User
Listing users
Sending message / object
Receiving message / object
Broadcast etc

Timer doesn't work in Azure Functions

After deploying the latest Timer sample to Azure Functions with V1 runtime, below exception will be thrown. We are working with Azure Functions team to find a solution to this issue. Progress will be updated here.

Exception while executing function: Functions.TimerFunction
Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.TimerFunction ---> System.AggregateException : One or more errors occurred. ---> The type initializer for 'System.IdentityModel.Tokens.Jwt.JsonExtensions' threw an exception. ---> Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.
   at Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetTaskResult(Task task) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 464
   at Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.<>c.<InvokeCore>b__27_0(Task t) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 287
   at System.Threading.Tasks.ContinuationResultTaskFromTask`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 287
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\FunctionInvokerBase.cs : 90
   at async Microsoft.Azure.WebJobs.Host.Executors.VoidTaskMethodInvoker`2.InvokeAsync[TReflected,TReturnType](TReflected instance,Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync[TReflected,TReturnValue](Object instance,Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,ParameterHelper parameterHelper,CancellationTokenSource timeoutTok… 

Can' get the sample to work. 'Failed to start connection'

When i follow the steps of "Build Your First Azure SignalR Service Application" tutorial,
i get the following exception on running the web app:

Microsoft.AspNetCore.Http.Connections.Client.HttpConnection[11]
      Failed to start connection. Error starting transport 'WebSockets'.
System.Net.WebSockets.WebSocketException (0x80004005): Unable to connect to the remote server ---> System.Net.Http.HttpRequestException: Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer
bestimmten Zeitspanne nicht richtig reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da der verbundene Host nicht reagiert hat ---> System.Net.Sockets.SocketException: Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer bestimmten Zeitspanne nicht richtig reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da der verbundene Host nicht reagiert hat
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketHandle.ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
   at System.Net.WebSockets.WebSocketHandle.ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
   at System.Net.WebSockets.ClientWebSocket.ConnectAsyncCore(Uri uri, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.Connections.Client.Internal.WebSocketsTransport.StartAsync(Uri url, TransferFormat transferFormat)
   at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.StartTransport(Uri connectUrl, HttpTransportType transportType, TransferFormat transferFormat)

(sorry for the german exception message in there, i don't know how to set them english)

Anyone else facing this problem?

ChatRoomLocal readme seems to be missing something

When following all the instructions, on dotnet run, the webpage displays Hello world!.
It might be helpful to indicate to have to comment/remove that part from the Startup.cs just in case...?

// app.Run(async (context) =>
            // {
            //     await context.Response.WriteAsync("Hello World!");
            // });

as shown below

screen shot 2018-05-09 at 21 57 38

Service crashes very easily with a tiny load

Hi, im currently testing ASR running with 2 units in serverless mode. A function handles the negotiation.

Connecting 300-500 clients over 10 seconds takes the service down 99% of the time. And if it was to handle all connections, alla clients gets disconnected after a minute, when they reconnect they take it down again.

Im running a simple console app to create the connections.

The errors im getting are

"SignalR connection failed to connect: Unable to connect to the server with any of the available transports. (WebSockets failed: The server returned status code '404' when status code '101' was expected.) (ServerSentEvents failed: Response status code does not indicate success: 404 (Not Found).) (LongPolling failed: Response status code does not indicate success: 404 (Not Found).)"

and

"SignalR connection failed to connect: Response status code does not indicate success: 503 (Service Temporarily Unavailable)."

My Function that handles negotiations barely even raises its cpu, and responds instantly on all requests.

tell me what you need to investigate in this issue.

How to generate accesstoken for SignalR Rest APIs

Hi,

I was redirected to these samples from this doc for signalR REST Api reference.

This sample has deprecation warning stating not to generate access token by themselves, but to use Management SDK.
This SDK is only available in C# and my backend is in node.js.

I tried using signalR input binding in azure functions, ref and tried using access token generated by negotiation endpoint, but it threw authorization error.

What is the best way to generate access token for signalR Rest APIs in node js stack?

Azure sample gives error when calling $.connection.hub.start()

I followed the local chat room sample, and it worked fine.

I then tried modifying it to use Azure, as shown in the Azure chat room sample.

My changes were to modify Startup.cs to call app.MapAzureSignalR(GetType().FullName) instead of app.MapSignalR() and to add the connection string to my web.config file (see below).

However, this does not work. When I load the page and enter my name, I see the following error in the browser's console window...

app.MapSignalR()Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
at hubConnection.fn.init. (jquery.signalR-2.4.0.js:2997)
at hubConnection.fn.init. (jquery.signalR-2.4.0.js:877)
at hubConnection.fn.init.handle (jquery-1.6.4.min.js:3)
at hubConnection.fn.init.k (jquery-1.6.4.min.js:2)
at Object.trigger (jquery-1.6.4.min.js:3)
at init.triggerHandler (jquery-1.6.4.min.js:3)
at Object.triggerReceived (jquery.signalR-2.4.0.js:1599)
at Object. (jquery.signalR-2.4.0.js:1634)
at Function.each (jquery-1.6.4.min.js:2)
at Object.processMessages (jquery.signalR-2.4.0.js:1633)

This seems to happen in the call to $.connection.hub.start()

Anyone any ideas what's gone wrong? My full web.config (with sensitive data removed) is shown below...

<?xml version="1.0"
      encoding="utf-8"?>

<configuration>
  <connectionStrings>
    <add name="Azure:SignalR:ConnectionString"
         connectionString="Endpoint=https://something.service.signalr.net;AccessKey=MyAccessKey=;Version=1.0;" />
  </connectionStrings>

  <system.web>
    <compilation debug="true"
                 targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json"
                          publicKeyToken="30ad4fe6b2a6aeed"
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0"
                         newVersion="11.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Buffers"
                          publicKeyToken="cc7b13ffcd2ddd51"
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0"
                         newVersion="4.0.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Threading.Tasks.Extensions"
                          publicKeyToken="cc7b13ffcd2ddd51"
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0"
                         newVersion="4.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.ValueTuple"
                          publicKeyToken="cc7b13ffcd2ddd51"
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.2.0"
                         newVersion="4.0.2.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp"
                extension=".cs"
                type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                warningLevel="4"
                compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript"
                extension=".vb"
                type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                warningLevel="4"
                compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

Management SDK Sample

Plan

Negotiation Server

dotnet run -c <ConnectionString>

Use <HubName>/negotiate to redirect the client to ASRS.

SignalR Client

dotnet run -n <NegotiationServer>

Connect to negotiation server and redirect to ASRS.

Publishing Messages Using Management SDK

dotnet run -h <HubName> -c <ConnectionString>

In the process, publish messages with commands:

*********Usage*********
send user <User Id>
send users <User Id List (Seperate with ',')>
send group <Group Name>
send groups <Group List (Seperate with ',')>
usergroup add <User Id> <Group Name>
usergroup remove <User Id> <Group Name>
broadcast
***********************
...

Examples for .NET Core Console App?

Could you add an example on how to connect to Azure SignalR from a .NET Core Console App? All the examples are currently for ASP.NET / JavaScript and how the connection is setup from .NET Core is well hidden in the frameworks.

Migrate maps to Azure Maps

Being that this uses a bunch of Azure services, would make sense for this sample to also use Azure Maps instead of Bing Maps.

Sending messages to specific group is not working in Azure function based SignalR service

Azure SignalR service + Azure function based hubs

I am just wondering if sending message to specific group within connected clients is working at all for anyone? Broadcast is working well though! Likewise, sending message to a specific user within connected clients is also not working just like sending to a specific group of users. Not sure if I am missing something in this context. Any leads would be appreciated!

    [FunctionName("SendMessageToSpecificGroup")]
    public Task SendMessageToSpecificGroup(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] object message,
        [SignalR(HubName = "maintenancehub")] IAsyncCollector<SignalRMessage> signalRMessages)
    {
        var inputParameters = JsonConvert.DeserializeObject<GroupDTO>(message.ToString());

        return signalRMessages.AddAsync(
            new SignalRMessage
            {
                GroupName = inputParameters.GroupName,
                Target = "GroupSpecificMessageTargetCaller",
                Arguments = new[] { message }
            });
    }


    [FunctionName("BroadcastMessage")]
    public Task BroadcastMessage(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] object message,
        [SignalR(HubName = "maintenancehub")] IAsyncCollector<SignalRMessage> signalRMessages,
        ILogger logger)
    {

        logger.LogInformation($"message to be sent is:" + message);
        return signalRMessages.AddAsync(
            new SignalRMessage
            {
                Target = "BroadcastMessageTargetCaller",
                Arguments = new[] { message }
            });
    }

The target method i.e. 'GroupSpecificMessageTargetCaller' is never triggering in the client side javascript.
On the contrary broadcast message to all connected clients is working well though. Target method 'BroadcastMessageTargetCaller' in the html client is getting triggered in broadcast case.

Client side code

connection.on('BroadcastMessageTargetCaller', BroadcastMessageTargetCaller);
connection.on('GroupSpecificMessageTargetCaller', GroupSpecificMessageTargetCaller);

let counter = 0;
function BroadcastMessageTargetCaller(message) {
  message.id = counter++; // vue transitions need an id
  data.messages.unshift(message);
}

let groupCounter = 0;
function GroupSpecificMessageTargetCaller(message) {
  message.id = groupCounter++; 
  data.groupSpecificMessages.unshift(message);
}

Attaching complete source code for any further investigation.
Thanks in advance!

AzureFunctonBasedSignalRService.zip

Server code-->

namespace MyFirstAzureFunction
{
public class MaintenanceHub : ServerlessHub
{

    Dictionary<string, string> groupsDictionary = new Dictionary<string, string>();

    #region "SignalR Triggers"

    [FunctionName("negotiate")]
    public  SignalRConnectionInfo Negotiate(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req,
        ClaimsPrincipal claimsPrincipal,
        [SignalRConnectionInfo(HubName = "maintenancehub")] SignalRConnectionInfo connectionInfo, ILogger log)
    {
        return connectionInfo;
    }

    [FunctionName(nameof(OnConnected))]
    public async Task OnConnected([SignalRTrigger] InvocationContext invocationContext, ILogger logger)
    {
        await Clients.All.SendAsync("ClientMethod", invocationContext.ConnectionId);
        logger.LogInformation("Connection Id of the client is:" + invocationContext.ConnectionId);
    }

    [FunctionName(nameof(OnDisconnected))]
    public void OnDisconnected([SignalRTrigger] InvocationContext invocationContext, ILogger logger)
    {
        logger.LogInformation($"{invocationContext.UserId} has disconnected");
    }

    #endregion

    #region "HTTP Triggers"


    [FunctionName("AddUserToGroup")]
    public Task AddUserToGroup(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] object userDetails,
        ClaimsPrincipal claimsPrincipal,
        [SignalR(HubName = "maintenancehub")] IAsyncCollector<SignalRGroupAction> signalRGroupActions,
        ILogger logger)
    {

        var loggedInUserDetails = JsonConvert.DeserializeObject<AddUserToGroupDTO>(userDetails.ToString());

        string[] userIdentifierData = loggedInUserDetails.UserName.Split(".", StringSplitOptions.None);

        if (!groupsDictionary.ContainsKey(userIdentifierData[0]))
        {
            groupsDictionary.Add(userIdentifierData[0], userIdentifierData[0]);
            logger.LogInformation($"New group is created with the name: " + userIdentifierData[0]);
        }

        logger.LogInformation($"User added under " + loggedInUserDetails.UserName + " group");
        //var userIdClaim = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);

        return signalRGroupActions.AddAsync(
            new SignalRGroupAction
            {
                UserId = loggedInUserDetails.UserName,//loggedInUserDetails.UserName,
                GroupName = userIdentifierData[0],
                Action = GroupAction.Add
            });
    }

    [FunctionName("BroadcastMessage")]
    public Task BroadcastMessage(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] object message,
        [SignalR(HubName = "maintenancehub")] IAsyncCollector<SignalRMessage> signalRMessages,
        ILogger logger)
    {

        logger.LogInformation($"message to be sent is:" + message);
        return signalRMessages.AddAsync(
            new SignalRMessage
            {
                Target = "BroadcastMessageTargetCaller",
                Arguments = new[] { message }
            });
    }


        //await Clients.All.SendAsync("BroadcastMessageTargetCaller", new[] { message });

    [FunctionName("SendMessageToSpecificGroup")]
    public Task SendMessageToSpecificGroup(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] object message,
        [SignalR(HubName = "maintenancehub")] IAsyncCollector<SignalRMessage> signalRMessages)
    {
        var inputParameters = JsonConvert.DeserializeObject<GroupDTO>(message.ToString());

        return signalRMessages.AddAsync(
            new SignalRMessage
            {
                GroupName = inputParameters.GroupName,
                Target = "GroupSpecificMessageTargetCaller",
                Arguments = new[] { message }
            });
    }

    //await Clients.Group(inputParameters.GroupName).SendAsync("GroupSpecificMessageTargetCaller", new[] { message});

    [FunctionName("SendMessageToSpecificUser")]
    public Task SendMessageToSpecificUser(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] object message,
        [SignalR(HubName = "maintenancehub")] IAsyncCollector<SignalRMessage> signalRMessages,
        ILogger logger
        )
    {
        var inputParameters = JsonConvert.DeserializeObject<UserDTO>(message.ToString());
        return signalRMessages.AddAsync(
            new SignalRMessage
            {
                UserId = inputParameters.UserId,
                Target = "UserSpecificMessageTargetCaller",
                Arguments = new[] { message }
            });
    }


    #endregion

}

#region "Helper classes"

public class AddUserToGroupDTO
{

    public string UserName { get; set; }

}

public class GroupDTO
{

    public string Sender { get; set; }

    public string Text { get; set; }

    public string GroupName { get; set; }

}

public class UserDTO
{

    public string Sender { get; set; }

    public string Text { get; set; }

    public string UserId { get; set; }

}

public class messageDTO
{
    public string Sender { get; set; }
    public string Text { get; set; }
}

#endregion

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.