I'm able to create a XMPP connection on page load. However whenever I move to another pages, I want to use the same connection to remove recurring notifications in client. I've used following code.
$(document).bind('connect', function (ev, data) {
var jid = $.jStorage.get('JID', null);
var sid = $.jStorage.get('SID', null);
var rid = $.jStorage.get('RID', null);
if ((jid != null) && (sid != null) && (rid != null)) {
var conn = new Strophe.Connection("http://localhost:5280/xmpp-httpbind");
conn.attach(jid, sid, rid, function () {
alert('Connection attach success.');
Gab.connection = conn;
});
}
else {
var conn = new Strophe.Connection("http://localhost:5280/xmpp-httpbind");
conn.connect(data.jid, data.password, function (status) {
if (status === Strophe.Status.CONNECTED) {
$(document).trigger('connected');
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger('disconnected');
}
});
Gab.connection = conn;
}
});
And in unload:
$(window).unload(function () {
if (Gab.connection != null) {
Gab.connection.pause();
$.jStorage.set('JID', Gab.connection.jid);
$.jStorage.set('SID', Gab.connection.sid);
$.jStorage.set('RID', Gab.connection.rid);
} else {
$.jStorage.flush();
}
// Gab.connection = null;
alert('paused/disconnected');
})
It attaches to connection, however as soon as it attaches, it says (POST http://localhost:5280/xmpp-httpbind 404 Not Found 36ms) in Firebug console. Any ideas?
Thanks in advance.
You should not trust unload. Instead store/update your RID on every cb from the xmpp server. Make sure your RID is getting incremented on each call as well.
Make sure to inspect the body of the message. Some XMPP servers return HTTP 404 on terminate.
Related
Dart Language:
This is plugin issue
xmpp_stone plugin
I can't fix this issue
anyone known please replay
[![enter image description here]
https://i.stack.imgur.com/FHe0O.png
Dart Language:
This is plugin issue
xmpp_stone plugin
I can't fix this issue
anyone known please replay
[![enter image description here]
https://i.stack.imgur.com/FHe0O.png
This is full code issue in xmpp_stone plugin
import 'dart:io';
import 'package:xmpp_stone/src/logger/Log.dart';
import 'package:console/console.dart';
import 'dart:async';
import 'dart:convert';
import 'package:xmpp_stone/xmpp_stone.dart' as xmpp;
import 'package:image/image.dart' as image;
final String TAG = 'example';
class ExampleConnectionStateChangedListener implements xmpp.ConnectionStateChangedListener {
late xmpp.Connection _connection;
late xmpp.MessagesListener _messagesListener;
StreamSubscription<String>? subscription;
ExampleConnectionStateChangedListener(xmpp.Connection connection, xmpp.MessagesListener messagesListener) {
_connection = connection;
_messagesListener = messagesListener;
_connection.connectionStateStream.listen(onConnectionStateChanged);
}
#override
void onConnectionStateChanged(xmpp.XmppConnectionState state) {
if (state == xmpp.XmppConnectionState.Ready) {
Log.d(TAG, 'Connected');
_connection.getMamModule().queryAll();
var vCardManager = xmpp.VCardManager(_connection);
vCardManager.getSelfVCard().then((vCard) {
if (vCard != null) {
Log.d(TAG, 'Your info' + vCard.buildXmlString());
}
});
var messageHandler = xmpp.MessageHandler.getInstance(_connection);
var rosterManager = xmpp.RosterManager.getInstance(_connection);
messageHandler.messagesStream.listen(_messagesListener.onNewMessage);
sleep(const Duration(seconds: 1));
var receiver = 'yyy#gmail.com';
var receiverJid = xmpp.Jid.fromFullJid(receiver);
rosterManager.addRosterItem(xmpp.Buddy(receiverJid)).then((result) {
if (result.description != null) {
print("TAG, 'add roster'" + result.description!);
}
});
sleep(const Duration(seconds: 1));
vCardManager.getVCardFor(receiverJid).then((vCard) {
if (vCard != null) {
print("TAG, 'Receiver info'" + vCard.buildXmlString());
if (vCard != null && vCard.image != null) {
var file = File('test456789.jpg')..writeAsBytesSync(image.encodeJpg(vCard.image!));
print("TAG, IMAGE SAVED TO: ${file.path}");
}
}
});
var presenceManager = xmpp.PresenceManager.getInstance(_connection);
presenceManager.presenceStream.listen(onPresence);
}
}
void onPresence(xmpp.PresenceData event) {
Log.d(TAG, 'presence Event from ' + event.jid!.fullJid! + ' PRESENCE: ' + event.showElement.toString());
}
}
Stream<String> getConsoleStream() {
return Console.adapter.byteStream().map((bytes) {
var str = ascii.decode(bytes);
str = str.substring(0, str.length - 1);
return str;
});
}
class ExampleMessagesListener implements xmpp.MessagesListener {
#override
void onNewMessage(xmpp.MessageStanza? message) {
if (message!.body != null) {
Log.d(TAG ,format(
'New Message from {color.blue}${message.fromJid!.userAtDomain}{color.end} message: {color.red}${message.body}{color.end}'));
}
}
#override
void onChatMessage(xmpp.MessageStanza? message) {
print(message);
if (message!.body != null) {
Log.d(TAG,format(
'New Message from {color.blue}${message.fromJid!.userAtDomain}{color.end} message: {color.red}${message.body}{color.end}'));
}
}
}
sendmessageforxmpp(){
var userAtDomain = 'xxx#gmail.com';
var password = 'password';
var jid = xmpp.Jid.fromFullJid(userAtDomain);
var account = xmpp.XmppAccountSettings(userAtDomain, jid.local,
jid.domain, password, 5222, resource: 'xmppstone');
var connection = xmpp.Connection(account);
var receiver = 'yyy#gmail.com';
var receiverJid = xmpp.Jid.fromFullJid(receiver);
Log.d(TAG, receiverJid.fullJid.toString());
var messageHandler =
xmpp.MessageHandler.getInstance(connection);
messageHandler.sendMessage(receiverJid, "str");
}
Your problem is that you are not using xmpp_stone correctly and therefore ends up in a situation where the internal state of xmpp_stone does not match what the developer of the package have intended.
I do, however, think the package are badly designed in such a way that wrong usage are very likely to happen so I would not blame you for getting into trouble.
The problem is the following in your code:
var connection = xmpp.Connection(account);
// ..
var messageHandler = xmpp.MessageHandler.getInstance(connection);
messageHandler.sendMessage(receiverJid, "str");
You are here creating a Connection but the underlying socket are never created. The default value for the internal state of Connection are XmppConnectionState.Idle. But when you are later trying to sendMessage, your code ends up running this from the package:
void write(message) {
Log.xmppp_sending(message);
if (isOpened()) {
_socket!.write(message);
}
}
bool isOpened() {
return state != XmppConnectionState.Closed &&
state != XmppConnectionState.ForcefullyClosed &&
state != XmppConnectionState.Closing &&
state != XmppConnectionState.SocketOpening;
}
The isOpened() ends up returning true since it sees XmppConnectionState.Idle as an open state where messages are allowed to be sent.
But that is not the case here since we never asked Connection to open actually do any connection and therefore _socket ends up being null. Since the package are trying to do ! on null, the application crashes.
For an actual solution, we can get inspired from the example implementation from xmpp_dart:
https://github.com/vukoye/xmpp_dart/blob/master/example/example.dart
We can here see they have a connection.connect(); call. But, I am going to guess this really only works because the example are not going to use the connection right after this call. The problem is that it is implemented like the following:
void connect() {
if (_state == XmppConnectionState.Closing) {
_state = XmppConnectionState.WouldLikeToOpen;
}
if (_state == XmppConnectionState.Closed) {
_state = XmppConnectionState.Idle;
}
if (_state == XmppConnectionState.Idle) {
openSocket();
}
}
Future<void> openSocket() async {
connectionNegotatiorManager.init();
setState(XmppConnectionState.SocketOpening);
try {
return await Socket.connect(account.host ?? account.domain, account.port)
.then((Socket socket) {
// if not closed in meantime
if (_state != XmppConnectionState.Closed) {
setState(XmppConnectionState.SocketOpened);
So connect() returns void but calls openSocket() which does return a Future that would be able to tell us when the connection are actually ready.
I would therefore instead suggest using openSocket() directly and make your sendmessageforxmpp() method async so we can await on the connection being open.
So your code should look like:
Future<void> sendmessageforxmpp() async {
var userAtDomain = 'xxx#gmail.com';
var password = 'password';
var jid = xmpp.Jid.fromFullJid(userAtDomain);
var account = xmpp.XmppAccountSettings(
userAtDomain, jid.local, jid.domain, password, 5222,
resource: 'xmppstone');
var connection = xmpp.Connection(account);
await connection.openSocket(); // <--- the important change :)
var receiver = 'yyy#gmail.com';
var receiverJid = xmpp.Jid.fromFullJid(receiver);
Log.d(TAG, receiverJid.fullJid.toString());
var messageHandler = xmpp.MessageHandler.getInstance(connection);
messageHandler.sendMessage(receiverJid, "str");
}
This error is usually occurring when you use the bang operator (!) on a nullable value that was not properly initialized, like
yourvariable!.somefield
The above assumes that yourvariable will not be null as this point. If it's null, then reality is in conflict with the assumption I have just described.
I had been working with Espruino for a bit and it is really a wonderful project. But, I am facing an issue for saving the code onto the flash, so that it can still be run when power is supplied to the board(NodeMCU), instead of the PC COM port. The code works completely fine until it is passed from the terminal. But, if I switch over the power supply it stops working.
Also, I tried the save() and E.on('init',function(){}) but to no avail. It still doesn't create a web server. If someone could help out here it could be great!
Thanks!
function main() {
var http = require('http');
var led = Pin(5);
http.createServer(function (req, res) {
var url = req.url;
res.writeHead(200);
if(url == "/on") {
digitalWrite(led, 1);
res.end("on");
} else if(url == "/off") {
digitalWrite(led, 0);
res.end("off");
} else {
res.end('Lol');
}
}).listen(80);
}
E.on('init', function(){
main();
});
Here's the code I wish to write to my flash for the IOT project I am working on
After fiddling around with the documentation and crawling the scrambled web for almost a whole day I found out a solution myself. The issue ->
function main() {
var wifi = require('Wifi');
wifi.startAP("testing");
wifi.save();
var http = require('http');
var led = Pin(5);
return http.createServer(function (req, res) {
var url = req.url;
res.writeHead(200);
if(url == "/on") {
digitalWrite(led, 1);
res.end("on");
} else if(url == "/off") {
digitalWrite(led, 0);
res.end("off");
} else {
res.end('Lol');
}
}).listen(80);
}
function test() {
console.log('Starting server');
setTimeout(function() {
var server = main();
console.log(server);
}, 5000);
}
E.on('init', function(){
test();
});
save();
The problem was that the MCU couldnot get enough time to connect to the wifi before the command for http.createServer() is executed. Since, it cannot obtain the ip address for the MCU, thus it is unable to process the http.createServer() command. Hence, a timeout was necessary to process a delay before it's execution.
I'm attempting to detect whether a connection refused error is taking place with the following tutorial: https://www.dartlang.org/dart-by-example/#http-requests-and-responses ; However, I continue to receive the method not found exception and cannot receive any feedback whether my HTTP Response was working or not. Any ideas would be appreciated. Please let me know if you need more information. --ignore "shroot".
handleFailure(error) {
print('Something went wrong.');
print(error.message);
}
void loadData(String url) {
//url = "${baseRestfulUrl}"+ QUERY_ALL_TARGET_ASSETS_BASE_URL;
print(url);
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
request.catchError(handleFailure);
if (request == null) {
var warn = (shroot.querySelector('#warning')
..text = "No records could be found to match the search criteria."
..style.color = "Red");
ButtonElement resetBtn = shroot.querySelector("#reset-btn");
resetBtn.disabled = true;
}
else if(request == 404)
{
var warn = (shroot.querySelector('#warning')
..text = "Error serving data. Please restart server."
..style.color = "Red");
}
else if(request == "ERR_CONNECTION_REFUSED")
{
var warn = (shroot.querySelector('#warning')
..text = "Error serving data. Please restart server."
..style.color = "Red");
}
else if(request != null)
{
var warn = (shroot.querySelector('#warning')
..text = ""
..style.color = "#fff");
ButtonElement resetBtn = shroot.querySelector("#reset-btn");
resetBtn.disabled = false;
}
else {
var warn = (shroot.querySelector('#warning')
..text = "Error serving data. Please restart server."
..style.color = "Red");
ButtonElement resetBtn = shroot.querySelector("#reset-btn");
resetBtn.disabled = false;
}
}
The link you added is about Dart I/O and Command Line Apps. This doesn't apply to Dart in the browser.
Dart has to delegate to the browser API with limited capabilities and therefore there are differences.
In the case of an error an instance of ProgressEvent is passed to this method
handleFailure(error) {
print('Something went wrong.');
// print(error.message); // ProgressEvent doesn't have a `message` getter
// the progress event doesn't provide any further information
if(error is ProgressEvent && (error as ProgressEvent).type == 'error') {
print('An error has occured'); // as we already know because `handleFailure()` was called
}
}
this code
if (request == null) {
is actually called before the request was sent because it is not inside a .then
var request = HttpRequest.getString(url).then(onDataLoaded);
request.catchError(handleFailure)
.then((e) {
if(request == null) { // doesn't make sense because you just assigned a value to request
...
}
});
I have created a ASP.Net Web API project and using this link. NServiceBus is integrated with web api. Here is my configuration at web api as a client.
Configure.Serialization.Xml();
Configure.Transactions.Enable();
Configure.With()
.DefineEndpointName(Constants.ClientName)
.DefaultBuilder()
.ForWebApi()
.Log4Net()
.UseTransport<Msmq>()
.PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(false)
.CreateBus()
.Start();
This is how I'm sending message to Server
var response = await Bus.Send(Constants.ServerName, request)
.Register<ResponseModel>((NServiceBus.CompletionResult completionResult) =>
{
ResponseModel responseMessage = null;
if (completionResult != null && completionResult.Messages.Length > 0)
{
var status = completionResult.Messages[0] as RequestStatus?;
if (status == RequestStatus.Successful)
{
responseMessage = TransactionManager.TransactionDictionary[request.RequestId].ResponseModel;
}
}
return responseMessage;
});
This is how I'm sending response from Server. I have commented some lines to show what I have already tried.
public void Handle(RequestModel message)
{
ProcessRequest(message).RunSynchronously();
}
private async Task ProcessRequest(RequestModel message)
{
....
ResponseModel response = new ResponseModel();
response.RequestId = message.RequestId;
response.Result = await responseMessage.Content.ReadAsStringAsync();
//Bus.Send(Util.Constants.ClientName, response);
//Bus.Reply(response);
//Bus.Reply<ResponseModel>((ResponseModel response) =>
//{
// response = Bus.CreateInstance<ResponseModel>(r =>
// {
// r.RequestId = message.RequestId;
// r.Result = responseMessage.Content.ReadAsStringAsync().Result;
// });
//});
await Bus.Send(Util.Constants.ClientName, response).Register((NServiceBus.CompletionResult completionResult) =>
{
if (completionResult != null && completionResult.Messages.Length > 0)
{
var msg = completionResult.Messages[0];
if (msg != null)
{
var status = (RequestStatus)msg;
return status;
}
}
return RequestStatus.Error;
});
....
}
From any of the above response methods ultimately all messages end up in error queue.
Previously I was getting 'Could not enlist message' error. Now it is not throwing that error. But Server could not send message to Client.
I could not get what I'm doing wrong. Please also suggest if you see any scope for improvements.
I'm not sure if TransactionScope work correctly with async/await in C#. According to this question (Get TransactionScope to work with async / await) in .NET 4.5.1 there was introduced option for TransactionScope that enable mixing it with async/await. Unfortunately NServiceBus doesn't support .NET 4.5/4.5.1 so try just remove async/await.
Is there any way to send/get the http headers (like, content-type... ) through AJAX?. Then, can please explain me, what will we archive by passing the http headers in AJAX and where will use this technique?.
Thanks
I'm no expert,
But you should look at the AJAX object XmlHttpHeader and the wikipedia article here.
EDIT: quoting the www.w3.org reference:
function test(data) {
// taking care of data
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseXML != null && this.responseXML.getElementById('test').firstChild.data)
// success!
test(this.responseXML.getElementById('test').firstChild.data);
else
test(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
test(null);
}
}
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.xml");
client.send();
If you just want to log a message to the server:
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(message);
}
Or if you want to check the status of a document on the server:
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this.status);
}
client.open("HEAD", address);
client.send();
}