In Firebase Realtime Database, if a client socket disconnects can I manually reconnect it for them? - firebase-realtime-database

I have a card game where I see some client sockets disconnect and the game gets hung up. Client observer(s) will miss a database event which hangs the game, but then continue seeing new updates after. So presumably the socket re-connected itself.
I am logging disconnects and app minimized states. Disconnects occur without client minimizing or closing app. When this happens, can/should I attempt to re-connect the socket manually and/or re-call any observers again to ensure when the socket re-connects any missed database events are captured. It seems during disconnect, any events during that time are missed.
{ "uniqueGameKey_ID_99987": {
"PlayedCards": {
"0": "ace_club",
"1": "king_spade",
"2": "ten_diamond"
},
"Msgs": {
"p1": "Hello",
"p2": "Hi"
},
"Score": {
"p1": 10,
"p2": 12
},
"ReadyUp": {
"p1": true,
"p2": false
}
}
I have observers on each node 'played cards', 'Msgs', 'Score', 'ReadyUp' and many more in the gameKey.
It seems client socket disconnects and does not see opponent "ReadyUp", and if it does reconnect, it may not be re-syncing that particular listener and game hangs.
Will any of the following help?
placing a "keepsynced()" on the readyUp listener
when client disconnects, call .goOnline() and re-run observers?
re-run observers if/when socket automatically re-connects?
Would love any advice here :)
Thank you!

Related

Twilio worker client disconnect reason

I'm trying to ensure single worker session/window at a time.
In order to achieve this I have added a parameter closeExistingSessions to the createWorker and it's disconnecting (websocket) the other workerClient as expected.
Just wondering if there is a way to know the disconnect reason using this disconnected event listener so that I can show a relevant message to the end user.
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
worker.on("disconnected", function(<ANY_ERROR_CODE_OR_SOMETHING_HERE?!>) {
console.log("Websocket has disconnected");
});
We are getting the reason (The reason the Worker websocket disconnected) as parameter to the disconnected callback.
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
worker.on("disconnected", function(reason) {
console.log(reason.message);
});
And the reason for disconnecting due to existing sessions is 'Websocket disconnected due to new connection being registered'
Hope Twilio will keep their docs up to date

Twilio voice callback

I'm having a tough time getting the Twilio Voice callback function to work properly, and would greatly appreciate any assistance in resolving this.
I have a working VOIP webapp using Python, twilio package and twilio voice SDK.
I need to get call status when a call is being made: answered, completed, ringing, in-progress and the likes.
is_record = fetch_recording_data_from_DB
handle_url = '/handle'
callback_url = '/events'
events = 'answered ringing initiated completed'
#incoming call
dial = Dial(timeout=15, record='record-from-ringing' if is_record else 'false', action=handle_url)
dial.client(
identity=contact_data['company_id'] or company_id,
status_callback_event = events,
status_callback = callback_url,
status_callback_method = 'POST'
)
return response.append(dial)
The handle_url is triggered after call ends or the 20s is exhausted with no answer to determine whether to make a call forwarding or play VM, this works fine. No error whatsoever, calls come in - I answer and talk for a while, if I don't, it goes to voicemail, records and hangs up. I see my recording, cost, duration and other data on the calls tab on Twilio console, under Monitor. All fine. I just can't get the status callback bit.
#status callback function
def stat_events():
return request.values, {'Content-Type': 'text/xml'}
.....
class StatEvents(Resource):
def post(self):
return stat_events()
Now, on the Twilio console, I can see the response and the other information (fromstate, sequencenumber,...) under Request Inspector (multiple times, as it should be) xdxxdxd.ngrok.io/events (POST, 200) regarding the call, but on my network tab (chrome) (when I make a call on the frontend) I check under the events network and see {} - empty
I tried console.log() on the events, nothing! so either I am not using this option well or there's something magical at play.
I need the status so I can save the call log to my DB (background task) when it's completed or no-answer.
data I want but it's only showing up on Twilio console and empty on network tab (apart from saving call log, I need this data to show the status on the front-end):
"Called": "+653xxxxxx",
"ParentCallSid": "CAd1ed07xxxxxxxxxxxxxxx",
"ToState": "",
"CallerCountry": "US",
"Direction": "outbound-dial",
"Timestamp": "Fri, 22 Jul 2022 08:58:56 +0000",
"CallbackSource": "call-progress-events",
"CallerState": "MI",
"ToZip": "",
"SequenceNumber": "0",
"CallSid": "CA3a39c6b1xxxxxxxxxxxxxx",
"To": "+653xxxxxxxx",
"CallerZip": "",
"ToCountry": "SG",
"CalledZip": "",
"ApiVersion": "2010-04-01",
"CalledCity": "",
"CallStatus": "initiated",
"From": "+194xxxxxxx",
"AccountSid": "ACb9f4fe8f52xxxxxxxxxxxxx",
"CalledCountry": "SG",
"CallerCity": "",
"ToCity": "",
"FromCountry": "US",
"Caller": "+1947xxxxxx",
"FromCity": "",
"CalledState": "",
"FromZip": "",
"FromState": "MI"
}```
```handle_url```'s function uses ```DialCallStatus``` in place of ```CallStatus```, as I read that this would be sent by Twilio request to the endpoint.
You describe that you are receiving requests to your /events webhook, but that you're not getting events in the browser.
When you register to receive events via a status_callback_url then those events are only sent as webhooks to your server.
However, if you have implemented the Twilio Voice SDK in JavaScript, then you can get call events by listening to events on the Twilio.Device object and on Twilio.Call objects. For example, the Twilio.Device will emit the incoming event when there is a new incoming call. And the Twilio.Call will emit accept events when an incoming call is accepted, and disconnect for when a call is over.
You can use these events to show call progress in your UI.
Events looks to be a list:
status_callback_event=['initiated', 'answered']

How to let Lettuce notify application when connection is down?

We are using Lettuce in our project. We have a requirement to monitor the status of connection.
I know Lettuce can re-connect Redis when the connection is down. But is there some way to notify application that the connection is down/up?
Thanks,
Steven
Lettuce provides an event-model for connection events. You can subscribe to the EventBus and react to events published on the bus. There are multiple events, but for your case, you'd want to listen to connected and disconnected events:
ConnectionActivatedEvent: The logical connection is activated and can be used to dispatch Redis commands (SSL handshake complete, PING before activating response received)
ConnectionDeactivatedEvent: The logical connection is deactivated. The internal processing state is reset and the isOpen() flag is set to false.
Both events are fired after receiving Transport-related events such as ConnectedEvent respective DisconnectedEvent.
The following example illustrates how to consume these events:
RedisClient client = RedisClient.create()
EventBus eventBus = client.getresources().eventBus();
Disposable subscription = eventBus.get().subscribe(e -> {
if (e instanceOf ConnectionActivatedEvent) {
// …
}
});
…
subscription.dispose();
client.shutdown();
Please note that events are dispatched asynchronously. Anything that happens in the event listener should be non-blocking (i.e. if you need to call blocking code such as further Redis interaction, please offload this task to a dedicated Thread).
Read more
Lettuce Reference Documentation: Events

Mosquitto should not store and send offline messages

I am trying not to get the offline messages my scenario is if client1 is offline and client2 is sending messages so client1 should not receive any old messages when he reconnects and he should receive messages sent after reconnection. I am using mqtt library(npm) on client side and mosquitto server. I have tried {clean:true} and publish and subscribe using {qos:0} and its not working.This is my code
client2:
this.client = mqtt.connect(url, {
clean: true
}
this.client.publish("mqtt/location", JSON.stringify(data1) ,{qos: 0});
Client1:
this.client = mqtt.connect(url, {
clean: true
}
this.client.subscribe("mqtt/location", {qos: 0});
this.client.on("message", function(topic, payload) {
console.log(payload);
})
Thanks
If you are setting clean session to true, then the only other explanation is that the messages you are receiving were published with the retained bit set. There is nothing you can do to stop your client receiving those messages, but you can detect them. Any published message that you receive from the broker that has the retained bit set is "old".

Problems subscribing to a room (socket) with Socket.IO-Client-Swift and Swift, Sails.js on the Server

On Swift, I use
socket.on("test") {data, ack in
print(data)
}
In order to subscribe to a room (socket) on my Sails.js API.
When I broadcast a message from the server, with
sails.sockets.broadcast('test', { text : 'ok' })
the socket.on handler is never called.
However, if I set "log" TRUE to config when connecting my socket.io client from swift, in Socket-IO logs the message arrives.
What's wrong?
Eventually, I found my mistake:
The whole process I did is right:
(The request to join the room is done by the server, with sails.sockets.join)
Wrong thing was using socket.on with the ROOM NAME parameter.
I will explain it better, for others having same problem:
From Swift you should subscribe by making a websocket request to an endpoint on the server that accepts websocket requests (GET, POST, PUT). For example, you can make a POST request, passing in the room name into the body.
socket.emitWithAck("post", [
"room": "testroom",
"url": "/api/v1.0/roomsubscribing"
]).timingOut(after: 0) {data in
print("Server responded with \(data)")
}
On server side, inside the room-subscribing endpoint, you should have the following code:
roomSubscribing: function(req, res) {
if (!req.isSocket) {
return res.badRequest();
}
sails.sockets.join(req, req.params('room'), function(err) {
if (err) {
return res.serverError(err);
}
});
}
When the server want to broadcast some data to subscribers of the "testroom" room, the following code must be used:
sails.sockets.broadcast('testroom', { message: 'testmessage' }
Now on the swift's side you must use:
socket.on("message") { data, ack in
print(data)
}
in order to get the message handler to work. I thought you should use room name, instead you should use the KEY of the KEY/VALUE entry you used in your server when you broadcasted the data (in this case, "message").
I only have a small amount of experience with sockets, but in case nobody else answers...
I think you are missing step one of the three step socket process:
A client sends a message to the server asking to subscribe to a particular room.
The client sets up a socket.on to handle particular events from that room.
The server broadcasts an event in a particular room. All subscribers/clients with a .on for that particular event will react.
I could be wrong, but it sounds from your description like you missed step one. Your client has to send a message with io.socket, something like here, then your server has to use the socket request to have them join the room, something like in the example here.
(the presence of log data without the socket.on firing would seem to confirm that the event was broadcast in the room, but that client was not subscribed)
Good luck!

Resources