signalr not working in client in .net mvc - signalr.client

i using signalr in my .net mvc project
browser log is:
[18:01:35 GMT+0330 (Iran Standard Time)] SignalR: Client subscribed to hub 'notificationhub'. jquery.signalR-2.2.1.min.js:9:3362
[18:01:35 GMT+0330 (Iran Standard Time)] SignalR: Negotiating with '/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22notificationhub%22%7D%5D'. jquery.signalR-2.2.1.min.js:9:3362
[18:01:35 GMT+0330 (Iran Standard Time)] SignalR: webSockets transport starting. jquery.signalR-2.2.1.min.js:9:3362
[18:01:35 GMT+0330 (Iran Standard Time)] SignalR: Connecting to websocket endpoint 'ws://localhost:3641/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=DiNre61g3xkbc1m99KZy8uhEaUK3FV0MpD4oiUxvyyser9qZpeA%2BUST3IVuvqQBfLFWc2TwSiy3MieDFXt1VWOcc2XPuL0soOC6kzikEprWOxyCo1AWeFByjXYPntuFC&connectionData=%5B%7B%22name%22%3A%22notificationhub%22%7D%5D&tid=9'. jquery.signalR-2.2.1.min.js:9:3362
[18:01:35 GMT+0330 (Iran Standard Time)] SignalR: Websocket opened. jquery.signalR-2.2.1.min.js:9:3362
[18:01:35 GMT+0330 (Iran Standard Time)] SignalR: webSockets transport connected. Initiating start request. jquery.signalR-2.2.1.min.js:9:3362
[18:01:35 GMT+0330 (Iran Standard Time)] SignalR: The start request succeeded. Transitioning to the connected state. jquery.signalR-2.2.1.min.js:9:3362
[18:01:35 GMT+0330 (Iran Standard Time)] SignalR: Now monitoring keep alive with a warning timeout of 13333.333333333332, keep alive timeout of 20000 and disconnecting timeout of 30000
[18:12:40 GMT+0330 (Iran Standard Time)] SignalR: Triggering client hub event 'receiveNotification' on hub 'notificationHub'
what is problem?

Client Codes:
<script>
$(function () {
$.connection.hub.logging = true;
var notificationHub = $.connection.notificationHub;
notificationHub.client.receiveNotification = function (message, userID, link) {
showNotification('new message', message, link);
};
$.connection.hub.start();
});
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, 5000); // Restart connection after 5 seconds.
});
</script>
<script type="text/javascript">
function notify(title,message,link) {
var option = {
body: message,
dir: 'rtl',
title:title,
icon:'/Content/Images/notification.png',
}
var notify = new Notification(title, option);
notify.onclick = function () {
window.open(link, '_blank');
notify.close();
};
}
function showNotification(title, message, link) {
if (!("Notification" in window)) {
//alert('Your browser does not support Notification');
} else if (Notification.permission === "granted") {
notify(title, message, link);
} else if (Notification.permission !== "denied") {
Notification.requestPermission(function (permission) {
if (permission === "granted") {
notify(title, message, link);
}
});
}
}
</script>

Related

.Net Core 3.1 SignalR Client Starts and Stops receiving messages at specific intervals

Does an Azure VM throttle SignalR messages being sent? Running locally, the client receives every message, but when hosted on the VM, clients only receive messages 30% of the time!?!?
This question is about Microsoft.AspNet.SignalR nuget package for SignalR in .Net Core 3.1 API back end, with a VueJS SPA front-end, all being hosted on an Azure Windows Server 2016 VM using IIS 10.
On my local machine, SignalR works perfectly. Messages get sent/received all the time, instantaneously. Then I publish to the VM, and when (IF) the WebSocket connection is successful, the client can only receive messages for the first 5 or so seconds at most, then stops receiving messages.
I've set up a dummy page that sends a message to my API, which then sends said message back down to all connections. It's a simple input form and "Send" button. After the few seconds of submitting and receiving messages, I need to rapidly submit (even hold down the "enter" button to submit) the form and send what should be a constant stream of messages back, until, low and behold, several seconds later messages begin to be received again, but only for a few seconds.
I've actually held down the submit button for constant stream and timed how long it takes to start getting messages, then again how long it takes to stop receiving. My small sample shows ~30 messages get received, then skips (does not receive) the next ~70 messages until another ~30 messages come in .. then the pattern persists, no messages for several seconds, then (~30) messages for a few seconds.
Production Environment Continuously Sending 1000 messages:
Same Test in Local Environment Sending 1000 messages:
If I stop the test, not matter how long I wait, when I hold the enter button (repeated submit), it takes a few seconds to get back into the 3 second/2 second pattern. It's almost as if I need to keep pressuring the server to send the message back to the client, otherwise the server gets lazy and doesn't do any work at all. If I slow play the message submits, it's rare that the client receives any messages at all. I really need to persistently and quickly send messages in order to start receiving them again.
FYI, during the time that I am holding down submit, or rapidly submitting, I receive no errors for API calls (initiating messages) and no errors for Socket Connection or receiving messages. All the while, when client side SignalR log level is set to Trace, I see ping requests being sent and received successfully every 10 seconds.
Here is the Socket Config in .Net:
services.AddSignalR()
.AddHubOptions<StreamHub>(hubOptions => {
hubOptions.EnableDetailedErrors = true;
hubOptions.ClientTimeoutInterval = TimeSpan.FromHours(24);
hubOptions.HandshakeTimeout = TimeSpan.FromHours(24);
hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(15);
hubOptions.MaximumReceiveMessageSize = 1000000;
})
.AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
// Adding Authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
// Adding Jwt Bearer
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = Configuration["JWT:ValidAudience"],
ValidIssuer = Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"])),
ClockSkew = TimeSpan.Zero
};
// Sending the access token in the query string is required due to
// a limitation in Browser APIs. We restrict it to only calls to the
// SignalR hub in this code.
// See https://learn.microsoft.com/aspnet/core/signalr/security#access-token-logging
// for more information about security considerations when using
// the query string to transmit the access token.
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/v1/stream")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
I use this endpoint to send back messages:
[HttpPost]
[Route("bitcoin")]
public async Task<IActionResult> SendBitcoin([FromBody] BitCoin bitcoin)
{
await this._hubContext.Clients.All.SendAsync("BitCoin", bitcoin.message);
return Ok(bitcoin.message);
}
Here is the Socket Connection in JS and the button click to call message API:
this.connection = new signalR.HubConnectionBuilder()
.configureLogging(process.env.NODE_ENV.toLowerCase() == 'development' ? signalR.LogLevel.None : signalR.LogLevel.None)
.withUrl(process.env.VUE_APP_STREAM_ROOT, { accessTokenFactory: () => this.$store.state.auth.token })
.withAutomaticReconnect({
nextRetryDelayInMilliseconds: retryContext => {
if(retryContext.retryReason && retryContext.retryReason.statusCode == 401) {
return null
}
else if (retryContext.elapsedMilliseconds < 3600000) {
// If we've been reconnecting for less than 60 minutes so far,
// wait between 0 and 10 seconds before the next reconnect attempt.
return Math.random() * 10000;
} else {
// If we've been reconnecting for more than 60 seconds so far, stop reconnecting.
return null;
}
}
})
.build()
// connection timeout of 10 minutes
this.connection.serverTimeoutInMilliseconds = 1000 * 60 * 10
this.connection.reconnectedCallbacks.push(() => {
let alert = {
show: true,
text: 'Data connection re-established!',
variant: 'success',
isConnected: true,
}
this.$store.commit(CONNECTION_ALERT, alert)
setTimeout(() => {
this.$_closeConnectionAlert()
}, this.$_appMessageTimeout)
// this.joinStreamGroup('event-'+this.event.eventId)
})
this.connection.onreconnecting((err) => {
if(!!err) {
console.log('reconnecting:')
this.startStream()
}
})
this.connection.start()
.then((response) => {
this.startStream()
})
.catch((err) => {
});
startStream() {
// ---------
// Call client methods from hub
// ---------
if(this.connection.connectionState.toLowerCase() == 'connected') {
this.connection.methods.bitcoin = []
this.connection.on("BitCoin", (data) => {
console.log('messageReceived:', data)
})
}
}
buttonClick() {
this.$_apiCall({url: 'bitcoin', method: 'POST', data: {message:this.message}})
.then(response => {
// console.log('message', response.data)
})
}
For the case when the Socket Connection fails:
On page refresh, sometimes the WebSocket Connection fails, but there are multiple calls to the Socket endpoint that are almost identical, where one returns 404 and another returns a 200 result
Failed Request
This is the request that failed, the only difference to the request that succeeded (below) is the content-length in the Response Headers (highlighted). The Request Headers are identical:
Successful request to Socket Endpoint
Identical Request Headers
What could be so different about the configuration on my local machine vs. the configuration on my Azure VM? Why would the client stop and start receiving messages like this? Might it be the configuration on my VM? Are the messages getting blocked somehow? I've exhausted myself trying to figure this out!!
Update:
KeepAlive messages are being sent correctly, but the continuous stream of messages sent (expecting received) only works periodically.
Here we see that the KeepAlive messages are being sent and received every 15 seconds, as expected.

addTrack after etablished connection

I need to add my track and send to other peers after having etablished the connection I've followed the MDN example
pc.onnegotiationneeded = async () => {
try {
makingOffer = true;
await pc.setLocalDescription();
signaler.send({ description: pc.localDescription });
} catch(err) {
console.error(err);
} finally {
makingOffer = false;
}
};
onnegotiationneeded is fired when we call pc.addTrack so I will remake the process offer -> answer -> ICE.
So I have a function which call getUserMedia and set the local video I've added a callback to apply addTrack to my peers
const handleActiveVideo = async (cb) => {
const devices = await getVideoDevices();
const localStream = await createLocalStream(devices[0].deviceId);
setLocalVideoEl(localStream, devices[0].deviceId);
cb((pc) => {
localStream.getTracks().forEach((track) => {
pc.connection.addTrack(track, localStream);
});
});
};
But if I do that with an etablished connection when I add my local stream to the track with one peer it's ok all work fine but with my second peer I have this error on Firefox
Remote description indicates ICE restart but offer did not request ICE
restart (new remote description changes either the ice-ufrag or
ice-pwd)
with Chrome
DOMException: Failed to execute 'setRemoteDescription' on
'RTCPeerConnection': Failed to set remote answer sdp: Failed to apply
the description for m= section with mid='0': Failed to set SSL role
for the transport.
To recapitulate
connect my 2 peers without any tracks on both sides
start the video with my Peer1 ok I can see the video with my Peer2
start the video with my Peer2 error on Peer2 in the answer
setRemoteDescription(description);

SignalR listener not getting invoked in React Native

I am building a mobile app in React Native for a backend written in .NET. The backend has implemented a realtime messaging service using SignalR Hubs. I am using the package react-native-signalr. The connection is getting established, and I can send message to SignalR hub by calling proxy.invoke. The problem is in reception of message. I tried with proxy.on but nothing happens.
componentDidMount(){
const { access_token } = this.props;
// Setup connection to signalr hub.
const hubUrl = `${API_URL}/signalr`;
const connection = signalr.hubConnection(hubUrl);
const proxy = connection.createHubProxy('MessagesHub', {queryParams: { token: access_token }});
// Start connection
connection.start();
// Trying to receive message from SignalR Hub
proxy.on('messageReceived', message => {
console.log(message);
})
proxy.on('sendPrivateMessage', message => {
console.log(message);
})
proxy.on('sentPrivateMessage', message => {
console.log(message);
})
}
when you register a listener with your_proxy.on function ,you must define a function with required parameters and bind it on constructor and then pass it to your_proxy.on function ,see bellow:
constructor(props){
super(props);
this.messageReceived=this.messageReceived.bind(this); // <========== **Important**
this.sendPrivateMessage=this.sendPrivateMessage.bind(this); // <========== **Important**
this.sentPrivateMessage=this.sentPrivateMessage.bind(this); // <========== **Important**
}
messageReceived(message ){
console.log(message);
}
sendPrivateMessage(message ){
console.log(message);
}
sentPrivateMessage(message ){
console.log(message);
}
componentDidMount(){
const { access_token } = this.props;
// Setup connection to signalr hub.
const hubUrl = `${API_URL}/signalr`;
const connection = signalr.hubConnection(hubUrl);
const proxy = connection.createHubProxy('MessagesHub', {queryParams: { token: access_token }});
// Trying to receive message from SignalR Hub
proxy.on('messageReceived', this.messageReceived);
proxy.on('sendPrivateMessage', this.sendPrivateMessage);
proxy.on('sentPrivateMessage', this.sentPrivateMessage);
// Start connection
connection.start();
}

Dart and RabbitMQ bind exchange

I use STOMP package, and I wrote a test:
test('can subscribe and send events to mq server', () async {
StompClient client2 = await serverClient.connect(mqIp,
port: mqPort, login: login, passcode: password);
client2.sendJson('Domain changed', {'a':'b'});
client2.disconnect();
StreamController controller = new StreamController();
Stream<String> stream = controller.stream.asBroadcastStream();
StompClient client1 = await serverClient.connect(mqIp,
port: mqPort, login: login, passcode: password);
client1.subscribeString("Entity changed", 'Domain changed',
(Map<String, String> headers, String message) {
controller.add(message);
}, ack: AUTO);
await for (String message in stream) {
String expectedEntity =
'{\"a\":\"b\"}';
expect(message, equals(expectedEntity));
break;
}
client1.unsubscribe("Entity changed");
client1.disconnect();
}, timeout: new Timeout(new Duration(seconds: 6)));
When I run pub run test I get Test timed out.
In RabbitMQ Managment in bindings section I get: (Default exchange binding) and zero in total messages:
Is it possible to send and recive messages in one channel?
If I use client1.subscribeString(ack: CLIENT,...) in RabbitMQ Managment I get one message "In memory" but test still Test timed out and I can't get message from mq.
Maybe I must set up amq.fanout exchange, but how I can do this?
Best choice for use RabbitMq with dart: mqtt package

how to get socketid in socket.io(nodejs)

In my nodejs application, i am using socket.io for sockets connection.
I am configuring my server side code like this
socket.io configuration in separate file.
//socket_io.js
var socket_io = require('socket.io');
var io = socket_io();
var socketApi = {};
socketApi.io = io;
module.exports = socketApi;
below is my server.js file in which i am attaching my socket io to the server like this
var socketApi = require('./server/socket_io');
// Create HTTP server.
const server = http.createServer(app);
// Attach Socket IO
var io = socketApi.io;
io.attach(server);
// Listen on provided port, on all network interfaces.
server.listen(port, () => console.log(`API running on localhost:${port}`));
and then i am using socket.io in my game.js file to emit updated user coins like this.
//game.js
var socketIO = require('../socket_io');
function updateUserCoins(userBet) {
userId = mongoose.Types.ObjectId(userBet.user);
User.findUserWithId(userId).then((user) => {
user.coins = user.coins - userBet.betAmount;
user.save((err, updatedUser) => {
socketIO.io.sockets.emit('user coins', {
userCoins: updatedUser.coins,
});
});
})
}
and then in my client side, i am doing something like this,
socket.on('user coins', (data) => {
this.coins = data.userCoins;
});
but with the above implementation, updating coins of any user, updates all user coins at the client side, since all the clients are listening to the same socket user coins.
To solve the above problem, i know that i have to do something like this,
// sending to individual socketid (private message)
socketIO.io.sockets.to(<socketid>).emit('user coins', {
userCoins: updatedUser.coins,
});
but my concern is that how will get <socketid> with my current implementation.
You can get it by listening to connection to your socket.io server :
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Here you have a socket object ( io.on('connection', function (socket) ) and you can get his id with socket.id
So you'll probably need to wrap your code with the connection listener.
Source of the exemple for the connection listener
Socket object description