I have correctly configured my Mosca Broker with an SSL certificate. I have verified that the server is running as the nmap command returns
8443 / tcp open https-alt
When I use the MQTT.js library with the following code, the browser returns the following error. Firefox can not establish a connection to the server in wss: //192.168.1.173: 8443 /.
I also do not receive the error in the connection. I do not know how to debug the error.
var client;
function loaded() {
var options = {
rejectUnauthorized: false
}
client = mqtt.connect('wss://192.168.1.173:8443', options)
client.on('connect', function () {
client.subscribe('presence')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
document.getElementById('lista').innerHTML = document.getElementById('lista').innerHTML + '<li>'+message.toString()+'</li>'
})
client.on('error', function (e) {
console.log(e);
})
}
Related
I have this Ionic 5/Capacitor app, which I'm making an API call to a local server from, that server running on docker at localhost:3000. When I test from the browser, the request is made fine. From Postman it requests fine, too. In my XCode logs the emulator, I see this
[error] - ERROR {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost:3000/pins","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:3000/pins: 0 Unknown Error","error":{"isTrusted":true}}
The really interesting part, is that I'm running Fiddler to monitor the request as it's made. Fiddler gets a 200 as well, I can even see the response data. So, Fiddler sees the proper network call, but then my Ionic app gets that error. That makes me feel like it's an Ionic/Emulator/IOS problem, but I don't have enough familiarity with Ionic to know right off the bat what it is.
Here's the code responsible for making the request:
ngOnInit() {
const request = this.http.get('http://localhost:3000/pins');
this.refresh$.subscribe(
(lastPos: { latitude?: any; longitude?: number }) => {
request.subscribe(data => {
if (data) {
this.addMarkersToMap(data, lastPos);
}
});
}
);
}
And the HTTPClient imported in the constructor is from Angular:
import { HttpClient } from '#angular/common/http';
I ended up having to use this package, doing a check on if I'm on mobile or not.
https://ionicframework.com/docs/native/http/
Try with this :
const request = this.http.get('http://localhost:3000/pins', { observe: 'response', withCredentials: true });
Solution 2 : capacitor.config.json
"server": {
"hostname": "localhost", (maybe try precising the port number too)
}
Solution 3 : On your Express server (from https://ionicframework.com/docs/troubleshooting/cors)
const express = require('express');
const cors = require('cors');
const app = express();
const allowedOrigins = [
'capacitor://localhost',
'ionic://localhost',
'http://localhost',
'http://localhost:8080',
'http://localhost:8100'
];
// Reflect the origin if it's in the allowed list or not defined (cURL, Postman, etc.)
const corsOptions = {
origin: (origin, callback) => {
if (allowedOrigins.includes(origin) || !origin) {
callback(null, true);
} else {
callback(new Error('Origin not allowed by CORS'));
}
}
}
// Enable preflight requests for all routes
app.options('*', cors(corsOptions));
app.get('/', cors(corsOptions), (req, res, next) => {
res.json({ message: 'This route is CORS-enabled for an allowed origin.' });
})
app.listen(3000, () => {
console.log('CORS-enabled web server listening on port 3000');
});
I'm new to React and Node and i'm trying to make a simple WebSocket using Socket.IO which gonna simply send greetings to all connected users and the user will respond to the server.
The Node.JS server is running on a Windows PC while the React-Native app is running on both iOS and Android devices.
Node.JS server code is the following
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : 'block',
database : 'visualpos'
});
// Creating a GET route that returns data from the 'users' table.
app.get('/prenotazioni', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query("SELECT Data, Importo_Doc FROM tabella_pagamenti", function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
connection.release();
});
});
app.get('/', function(req, res){
res.send('<h1>Hello World</h1>');
});
// Starting our server.
http.listen(3000, () => {
console.log('In ascolto sulla porta *:3000');
});
io.emit('saluta', 'Ciao dal server :)');
io.on('connected', (data) => {
console.log(data);
});
Actually GET part of the code works perfectly but the Socket.IO seems death.
The client doesn't get any response and server the same i think the Socket.IO server simply doesn't start..
In XCode Debug i get the following errors when the app is running on the iPhone
And i even get on both devices warning "Unrecognized WebSocket connection option(s) 'agent', 'perMessageDeflate',..."
And here is the code i'm using in React-Native
import io from 'socket.io-client'
var socket = io('http://192.168.100.50:3000', {
jsonp: false,
transports: ['websocket'],
autoConnect: true,
reconnection: true,
reconnectionDelay: 500,
reconnectionAttempts: Infinity
});
componentDidMount(){
socket.emit('connected','we');
socket.on('saluta',(data) => { alert(data); });
}
On socket.io getStarted section, they use a "connection" event instead of "connected" (https://socket.io/get-started/chat/).
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
I have a PhoneGap application and I want to open a socket to a endpoint using sockets-for-cordova plugin:
var socket = new Socket();
socket.open(
"192.168.2.1",
80,
function () {
// invoked after successful opening of socket
console.log("connection");
$scope.$apply();
},
function (errorMessage) {
// invoked after unsuccessful opening of socket
console.log("error");
$scope.$apply();
socket.shutdownWrite();
});
After I use this function to handle messages
socket.onData = function (data) {
// received message
}
On Android it works well, sending and receiving message, unfortunately on iOS it simply doesn't work, not receive any message at all or it close the socket itself.
I can see "connection" message, so I guess that the socket is created.
I've downloaded Mosca (^1.1.2), MQTT (via npm) and Paho. When I create a simple broker as shown here: http://thejackalofjavascript.com/getting-started-mqtt/ (last 3 codes). It works all fine. My problem is when I try to implement client in the browser using Paho. with this code:
// Create a client instance
var client = new Paho.MQTT.Client('127.0.0.1', 4883, "clientId-1");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
var options = {
//connection attempt timeout in seconds
timeout: 3,
//Gets Called if the connection has successfully been established
onSuccess: function () {
console.log("onConnect");
client.subscribe("testtopic/#");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
console.log("Connection failed: " + message.errorMessage);
}
};
// connect the client
client.connect(options);
// called when the client connects
function onConnect() {
console.log("onConnect");
client.subscribe("testtopic/#");
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log(message.payload);
}
I always get this message: "Connection failed: AMQJSC0001E Connect timed out."
When I change '127.0.0.1' to a online broker, it works. So, I'm guessing my problem is with allowing ports in my broker.
Does anyone know how to solve this problem?
I write application for iOS, which uses Socket.IO. Sometimes my server JS-script falls with this error:
events.js:85
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
What I know is:
Script workes fine when I use only application for Android. That app uses Socket.IO for Android
Script workes fine when I use only web-client (yeap, with socket.IO)
Script startes to fall when I use iOS app.
Crash happens not always and not right away. Script falls after 5-10 minutes after connection and may crash, but may not.
So, I think the problem is in server library for socket.io, but exception fires only when iOS-client connecting.
How can I handle this exception?
UPDATE
There is problem was in the OAuth module on my node.js-server, which tried to check app token but had timeout to vk.com
I've edited vkapi module in my node.js server by adding "on" event for "https.get" function:
Was:
https.get(options, function(res) {
var apiResponse = new String();
res.setEncoding('utf8');
res.on('data', function(chunk) {
apiResponse += chunk;
});
res.on('end', function() {
var o = JSON.parse(apiResponse);
if (o.error) { self.emit('appServerTokenNotReady', o);
} else {
self.token = o.access_token;
self.emit('appServerTokenReady');
}
});
});
Now:
https.get(options, function(res) {
var apiResponse = new String();
res.setEncoding('utf8');
res.on('data', function(chunk) {
apiResponse += chunk;
});
res.on('end', function() {
var o = JSON.parse(apiResponse);
if (o.error) { self.emit('appServerTokenNotReady', o);
} else {
self.token = o.access_token;
self.emit('appServerTokenReady');
}
});
}).on('error', function(e) {
console.log('HTTPS error');
});
In general, you can handle these kinds of async errors by listening for the error event on whatever (e.g. request, connection, etc.) object.
The error event is special in that if there are currently no event handlers for it when it is emitted, the error will be thrown instead.