Strophe Message Sent Acknowledgment Issue - javascript

I have implemented OPENFIRE with XMPP + BOSH on my Web based client interface.
When i am sending the message ,i check whether connection is live or not.If it is not live i create new connection and then send.
Sometimes it happens that client send a message and it is not get delivered to server(not opposite client).
So for that i need a strong thing that should inform client that this message didn't reach to server,please send again.
try { // sleep(2000);
Gab.connection.send(message); >
**var request = $msg({
to: jid,
"type": "get",
id: mid
}).c('get', {
'xmlns': Strophe.NS.DISCO_INFO,
'id': mid
});**
console.log(request); >
} catch (err) {
alert("Internet Disconnected ! Click ok to Reconnect SEND");
window.top.location.reload(1);
}
On above code i call message send().After that i call function as mentioned in "XMPP:xep-0184" doc.
but no response i received.
Thank you in advance.

Not sure what a "strong thing" is, but when someone is disconnected in Strophe, you should get errors from the script and it will update the Strophe.Status connection state. Strophe sends a post every 60 secs (unless otherwise specified). In your code it appears you're trying to check support.
You should look for "Strophe.Status.CONNECTED" or "Strophe.Status.ATTACHED" prior to sending if that's your concern. You can also write a handler to manage the errors.
In XEP 0184, you must include:
<request xmlns='urn:xmpp:receipts'/>
So your msg should look like (note, you must include an id per XEP 0184):
$msg({
to: tojid,
from: fromjid,
type: "chat",
id: "sometrackingid"}).c('body').t("bodytxt").up().c("request", {
xmlns: "urn:xmpp:receipts"});
You will then need to modify you message handler or create a separate handler to manage the receipts.

Related

How to resolve a buffered values issue in Websocket Rxjs? Sending a message doesn't go to the server but gets stored in buffer

I am using Websocket Rxjs in my application. My connection gets established with the server and after subscribing to it I receive all the data in an array. Now when I try to send the some data back to the server, it just doesn't send, it get's stored in the buffer array of destination object of websocket observable (screenshot below). I am sharing the snippet of the code also.
import { webSocket } from 'rxjs/webSocket';
const subject = webSocket('ws://localhost:8081');
subject.subscribe({
next: msg => console.log('message received: ' + msg),
error: err => console.log(err),
complete: () => console.log('complete')
});
// Upon clicking a button I send this to the sever. You can see it in the screenshot.
subject.next({
"action" : "read",
"id" : 1595
});
My connection remains active though. It doesn't gets closed but still I am facing this issue. What could be the issue with this? Is it something with the backend ? If yes, then what could it be ? Any help will be appreciated. Thank you. :)
It seems that the problem is in your websocket server, but to be sure try instead to connect to a test server like the echo server of Postman:
wss://ws.postman-echo.com/raw
In each time the client sends a message to this server it will send it back to the client directly.
By the way: Postman now has the possibility yo to connect to your websocket server and test it.
Here you can read how to do that:
https://blog.postman.com/postman-supports-websocket-apis/

Update chat with MySQL on JavaScript event

I'm trying to make a chat system where anyone can go into the chat and send a message. The messages are stored in a MySQL database and my code looks like this at the moment ...
<script>
$('input[type=text]').on('keydown', function(e) {
if(e.which == 13) {
e.preventDefault();
$.ajax({
url: "php/chat.class.php",
data: { steamid: "<?php echo $steamprofile['steamid']?>", message: document.getElementById("chatMessage").value },
type: "GET",
context: document.body
}).done(function() {
alert("Message sent");
// This is when the chat should update for everyone
}).error(function() {
document.getElementById('chat-box').innerHTML += '<span class="text-muted"><i>Could not send chat message at this time.</i></span>';
});
}
});
Basically, it inserts a new row into the MySQL table once you press enter.
As it is a chat for everyone, I need the chat to update for every user when anyone sends a message.
I know how to display all the messages and who sent them, but I need it to update whenever someone sends a message, for everyone.
I've done research but I can't find anything useful unfortunately and now I'm clueless.
I've thought of updating the chat every x seconds, but I want to make the chat as smooth and fast as possible and wondering what the best solution would be.
Have a good day
So that is a read operation, and hence what you are trying is a write operation. Either you can do a continuous lookup to the server with a interval/timeout/ or initiate a rest call when last call was finished (success/error/timeout whatever). but better approach for this will be initiating a WebSocket Client and create and set up WebSocket Server in your backend and design it properly, so if it get any message from any client it will send that to all other client or something optimizer/ or something in schedule
Consider using a realtime database like Firebase https://firebase.google.com/docs/database/web/start and on your client side you can listen to messages being added using something like:
commentsRef.on('child_added', function(data) {
addCommentElement(postElement, data.key, data.val().text, data.val().author);
});
With firebase you can create a serverless chat application.

Is there a way to know a Twilio call failed without calling the REST API?

I'm using Twilio.Device in an Angular app and I need to display a message if the call failed due to an invalid number. I know that you can call Twilio's REST API to get the call status, but is there a way to get the status without making that extra call?
For example, I was hoping that the connection object that you get back in the disconnect handler would give you the status, like this:
Twilio.Device.disconnect(function(connection) {
if (connection.status === 'failed') {
// display error message
}
});
However, that's either not possible or I'm not looking in the right place.
Another idea I had is when I set debug to true, I can see this helpful log when making a call with an invalid number:
[Connection] Received HANGUP from gateway
[Connection] Disconnecting...
But is there any way to access that HANGUP event?
Thanks in advance!
I'm not sure exactly which you'd need, but in the accept or connect methods, try listening for the 'hangup' or 'error' events which are emitted by the Connection class:
Twilio.Device.connect(function(connection) {
connection.on('hangup', function (err) {
console.log(err)
})
})
Twilio developer evangelist here.
You can actually get all the details that you would normally need the Twilio REST API for on the Twilio.Connection object. Just take a look at the parameters attribute, it contains all the normal Twilio voice request parameters including CallStatus.

HTML5 Event Source API and node.js | How to send the stream to the correct client?

For some reason, which I think there is no point mentioning, i can't use socket.io and i decided to use HTML5 Event Source API (Server-sent events) to sent a message to the client. The message tells the client that his payments has been received via a third-party callback.
I've got an ID that identifies each client and it is also received in the callback. I've got two questions so far:
I suppose every message sent is broadcasted to all the clients. Is there a way to select a specific client by his ID?
Currently i am implementing this functionality in the client using an if sentence, but if i could sent the message directly form server to the client to improve performance would be great
When i close the connection on the client i guess i am not closing all the connections stablished, isn't it?
My code:
Node.js
app.get('/payments', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
});
ee.on("payment", function (data) {
res.write("data: "
+ JSON.stringify({'wallet': data.address, 'refund_address': data.refund_address,'payment_status': 'paid'})
+ "\n\n"
);
});
});
Client
var source = new EventSource("/payments");
source.addEventListener('message', function(e) {
if (e.origin == 'http://localhost:3000') {
var data = JSON.parse(e.data);
if (btcwalletdir == data.wallet) { //each client filter
// do whatever here
source.close();
}
return;
}
}, false);
Is it a valid solution for a production environment?
Regards,
Regarding EventSource each client has its own connection. Each time someone access that endpoint it will have a request/response assigned to it, so when you do res.write you are only writing to one client.
But of course if you broadcast the event "payment" to every connection, each one will send the json message to the respective client. So you need to find a way to only send the data to the correct connection (ex adding a user/connection id to the data you emit and storing the res objects in an array/object)

Server XHR got received event in JS

Situation:
Target API is external and may not be changed in any way. I have a JS client that sends some data to the API on client button click. Something like
$.ajax({
type: "POST",
url: "http://api.url/some_resource",
data: {name: 'John', email: 'john#john.com'}
}).done(function(msg) {
if (msg === 'ok') {
alert('Your Callback Request Sent!');
} else {
alert('Error occurred. Please try later.');long
}
});
When I send the request I have to wait to receive the response from the server to see if it was successful and notify the client if it was or was not.
The problem is that I the API is friggin slow and does not reply directly that it received everything and will process the request, but instead is trying to do all the job like sending email and only then replying. Sometimes it takes about 20s for response to be received (the XHR request response).
Is it possible (jQuery or pure JS) to fire something like "request reached server event" so I would be at least sure there were no connection problems?
Is it possible to fire something like "request reached server event"
No - the client does not know of that event. It only knows a) when it has sent the last bit of the request and b) when it has received the first bit of the response. There is nothing in between but waiting.
To the XMLHttpRequest interface there is the following readyState information available:
Val State Description
---------------------------------------------------------------------------------
0 UNSENT open()has not been called yet.
1 OPENED send()has not been called yet.
2 HEADERS_RECEIVED send() has been called, and headers and status are available
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
so I would be at least sure there were no connection problems?
Well, if there had been connection problems that are detectable to the client, you would've been notified of them.

Categories