I have a client which receives messages over SignalR. It is working great but it is more like a broadcast. I would like to be able to send messages to a specific client. On the client-side I have a userId and I set up my connection like this:
JavaScript
x
12
12
1
const userId = getUserId();
2
3
if (userId) {
4
const beacon = new signalR.HubConnectionBuilder()
5
.withUrl(`${URL}/api?userId=${userId}"`)
6
.build();
7
8
beacon.on('newMessage', notification => console.log);
9
beacon.start().catch(console.error);
10
}
11
};
12
On the server-side (Azure Function written in JavaScript) I have a message and a userId. The question for me is how does the server know which SignalR connection is going to this specific user? Can I somehow tell SignalR who I am?
Advertisement
Answer
Using the Azure SignalR Service and the client-side code from the question I was able to get it to work. I used the following Azure Function to negotiate the connection:
JavaScript
1
5
1
module.exports = async function (context, req, connectionInfo) {
2
context.res.body = connectionInfo;
3
context.done();
4
};
5
JavaScript
1
24
24
1
{
2
"disabled": false,
3
"bindings": [
4
{
5
"authLevel": "anonymous",
6
"type": "httpTrigger",
7
"direction": "in",
8
"name": "req"
9
},
10
{
11
"type": "http",
12
"direction": "out",
13
"name": "res"
14
},
15
{
16
"type": "signalRConnectionInfo",
17
"name": "connectionInfo",
18
"userId": "{userId}", // <----- IMPORTANT PART!
19
"hubName": "chat",
20
"direction": "in"
21
}
22
]
23
}
24
As well as another function to send a message to a specific user:
JavaScript
1
9
1
module.exports = async function (context, req) {
2
const messageObject = req.body;
3
return {
4
"target": "newMessage",
5
"userId": messageObject.userId,
6
"arguments": [ messageObject.message]
7
};
8
};
9
JavaScript
1
26
26
1
{
2
"disabled": false,
3
"bindings": [
4
{
5
"authLevel": "anonymous",
6
"type": "httpTrigger",
7
"direction": "in",
8
"name": "req",
9
"methods": [
10
"post"
11
]
12
},
13
{
14
"type": "http",
15
"direction": "out",
16
"name": "res"
17
},
18
{
19
"type": "signalR",
20
"name": "$return",
21
"hubName": "chat",
22
"direction": "out"
23
}
24
]
25
}
26