I have implemented negotiate endpoint and send method and connected from signalR JS client. I am getting the connection and able to broadcast message to all connected clients. As per our requirement, I have to send the message to a few clients. From the documentation, I believe we can send messages to a group. I have written an azure function for Adding and removing a user to a group.
[FunctionName("AddToGroup")]
public static Task AddToGroup(
[HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req,
ILogger log,
[SignalR(HubName = NotificationConstants.Hub)]IAsyncCollector<SignalRGroupAction> signalRGroupActions)
{
string userId = req.Query[NotificationConstants.QueryStringUserId];
string companyId = req.Query[NotificationConstants.QueryStringCompanyId];
return signalRGroupActions.AddAsync(
new SignalRGroupAction
{
UserId = userId,
GroupName = string.Format(CultureInfo.CurrentCulture,
NotificationConstants.Group,
companyId),
Action = GroupAction.Add
});
}
[FunctionName("RemoveFromGroup")]
public static Task removeFromGroup(
[HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req,
ILogger log,
[SignalR(HubName = NotificationConstants.Hub)]IAsyncCollector<SignalRGroupAction> signalRGroupActions)
{
string userId = req.Query[NotificationConstants.QueryStringUserId];
string companyId = req.Query[NotificationConstants.QueryStringCompanyId];
return signalRGroupActions.AddAsync(
new SignalRGroupAction
{
UserId = userId,
GroupName = string.Format(CultureInfo.CurrentCulture,
NotificationConstants.Group,
companyId),
Action = GroupAction.Remove
});
}
How I can call this from JS Client? My sample client code as below. Please suggest
function GetConnectionInfo() {
return axios.get('http://localhost:7071/api/ConnectionInfo?UserId=1_2347')
.then(function (response) {
return response.data;
}).catch(console.error);
}
function StartConnection(connection) {
console.log('connecting...');
connection.start()
.then(function () {
console.log('connected!');
connection.invoke('getConnectionId')
.then(function (connectionId) {
console.log(connectionId);
// Send the connectionId to controller
});
})
.catch(function (err) {
console.error(err);
setTimeout(function () { StartConnection(connection); }, 2000);
});
}
GetConnectionInfo().then(function (info) {
let accessToken = info.accessToken;
const options = {
accessTokenFactory: function () {
if (accessToken) {
const _accessToken = accessToken;
accessToken = null;
return _accessToken;
} else {
return GetConnectionInfo().then(function (info) {
return info.accessToken;
});
}
}
};
const connection = new signalR.HubConnectionBuilder()
.withUrl(info.url, options)
.build();
StartConnection(connection);
connection.on('DocumentStatusUpdated', ProcessDocumentData);
connection.onclose(function () {
console.log('disconnected');
setTimeout(function () { StartConnection(connection); }, 5000);
});
}).catch(console.error);
Can someone please guide me.
Thanks