MQTT server to client communication - javascript

I want to communicate between server and client using mosca.At first case i subscribe and publish data from client.And receive that data into server.But i face some problem again i want publish the data from server and receive that data from same client.
Example: From front-end send same data to the server.After receiving those data i want store those data in database.After save the data i want send the some response(data) to the same client using Mosca(in Javascript).
Thanks for giving answer.

If you trying to use a MQTT client on browser you should use a option to activate websocket.
Something like this:
const mosca = require("./");
const server = new mosca.Server({
http: {
port: 3000, //use this port to connect
bundle: true,
static: './'
}
});

Related

Pass Twilio SMS Post Data from Node to React

I'm currently using Twilio to receive SMS messages on my server. I need to display the return data in React. Twilio only sends the data server side through a POST request. If I send a text from my phone. The Twilio POST request will be send the data to my server. How can I get the POST data sent to my React app? The below code is how I receive the data from Twilio.
app.post('/sms', (req, res) => {
var msgFrom = req.body.From;
var msgBody = req.body.Body;})
yes you can and there are two ways:
1- you can use the the HTTP regular request model, you can achieve this by sending a request checking for updates and if there is what and update the front end.
2- long polling or streams sockets to emit the data to your applications from the back end.

How would I create an android app with an array stored on a web server using android studio?

I am trying to make a 'shower thoughts' app. It has three categories stored in arrays. Underneath each are nested the actual list of user posts that the user can see (as arrays) . Of course, a user wont be able to see others posts. I have a rasbpi I am using as a webserver. The way I thought of doing this is a bit of javascript code on the web server that contain two functions: One that adds a users post to an array (with the input arguements being the post itself) and one that returns the array so that the app can update. However, I have no idea how to CALL this js file on the web server from the application. How would I do this?
You will have to construct a web API for this. You can do this using NodeJS on the server and then send requests to this API in Android
Basically what you are trying to do is create a simple Server-Client Architecture.
There are multiple ways to do so. I am going to explain using NodeJS as the server and volley on the client (android) side.
Firstly you can use Volley, to create an API call from android, that would interact with the NodeJS API, which in turn will create the array and store it in either SQL or any other form you want.
For reference you can check out this two projects.
This is an Android app which is using Volley to communicate with the server.
This is the NodeJS Server which is a simple REST API.
You can also use this link to learn basics about NodeJS if you don't know.
This is the basic NodeJS code to create a server and then send a response to the client.
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
This is the basic Android Volley code to make a request to the server.
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
textView.setText("Response is: "+ response.substring(0,5));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
If you don't understand any of these code you can comment below.

Web sockets, socket.io or other alternative

I'm kinda new on sockets related subject so I'm sorry for any dumb question.
I would like to do something like this… I have am hybrid app and a website, and I wanted that when I click in a button on the app, it shows me alert/notificaion on the website. I read about Socket io and it does the job on localhost, but I want na alternative that not uses a server behind, since I'm not being able to run it using CPANEL (What I have access to)
Is it possible to have like a "direct" connection from the app to the site when I click the button?
You can consider using firebase for this:
In your javascript:
// execute the following script on click
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
'messagingSenderId': 'YOUR-SENDER-ID'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.send({data: "your data if you want to send"}).then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
// similarly, on your browser:
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
// ...
});
link: https://firebase.google.com/docs/
Hope it helps
Let's break the problem down into a few parts, starting with the transport to the browser, as that's what you're asking about.
Web Sockets are a way to establish a bi-directional connection between a server and a client. It's a standard implemented by most any modern browser. Socket.IO is a web-socket-like abstraction that can use Web Sockets or other transports under the hood. It was originally built as sort of a polyfill, allowing messages to be sent via Web Sockets, or even long-polling. Using Socket.IO doesn't give you any additional capability than you have with just the browser, but it does provide some nice abstractions for "rooms" and such.
If you're sending data only from the server to the client, Web Sockets aren't the ideal choice. For streaming of data in general, the Fetch API and ReadableStream are more appropriate. Then, you can just make a normal HTTP connection. However, what you're looking for is event-style data, and for that there are Server-Sent Events (SSE). https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events Basically, you instantiate an EventSource object on the client, pointed at a URL on the server. The client automatically maintains a connection, reconnecting if necessary. It's also capable of synchronizing to a point in the stream, providing the server with the last message received so that the client can be caught up to present time.
Now, how does your server endpoint know when to send this data, and what to send? Ideally, you'll use some sort of pub/sub system. These capabilities are built into Redis, which is commonly used for this. (There are others as well, if you don't like Redis for some reason.) Basically, when your server receives something from the app, the app is "publishing" a message to a particular channel where all "subscribers" will receive it. Your server will be that EventSource and can simply relay data (verifying it and authenticating of course, along the way).
You can write a PHP script that has a POST/GET endpoint. Your app will communicate to this endpoint. The endpoint needs to handle the message and write it to a database. Your website can then poll to see if there are any new entries, and show something if there are
Alright, let's do it in PHP. This is just the most basic example. Just put it somewhere and link to the script from your app.
<?php
function requestVars($type = 'REQUEST'){
if($type == 'REQUEST')
$r = $_REQUEST;
elseif($type == 'POST')
$r = $_POST;
elseif($type == 'GET')
$r = $_GET;
$ret = array();
foreach($r as $r1 => $r2)
$ret[$r1] = $r2;
return $ret;
}
$vars = requestVars(); //get variables from request
echo $vars['var1']; // var1 is what comes in from the client
?>
I haven't tested this, so if something is wrong let me know.

Running a node.js file from website

I have recently started using the Twilio platform to send SMS to my users. I am perfectly able to run the node.js file from the node terminal with the command:
node twilio.js
Now, my goal is to be able to send those SMS, but from my website. For instance, when the user provides his phone number and presses the "Send sms" button. How can I achieve this? I have been looking this up for a while and I came across Express platform, ajax post requests, http server, etc. But, I can't figure out how to use them. I currently make many ajax requests (POST and GET) on my site, but I'm not able to make a request to a node file.
Thanks in advance,
Here is the twilio.js file:
// Twilio Credentials
var accountSid = 'ACCOUNT SID';
var authToken = 'ACCOUNT TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
client.messages.create({
to: 'TO',
from: 'FROM',
body: 'Message sent from Twilio!',
}, function (err, message) {
console.log(message.sid);
});
Being able to run any arbitrary script on your server from a webpage would be a huge security risk - don't do that. I'm not sure where you're hosting your site, or what technology stack you're running your site on, but since you mentioned Express and Node -- if you're using Express I'd recommend that you setup a route that handles an ajax request. When someone presses 'Send SMS' you send an ajax request to that route, and in the handler that gets invoked you place the Twilio logic.
Here is a very simple way to setup an Express request that calls you node module:
twilio.js:
// Twilio Credentials
var accountSid = 'ACCOUNT SID';
var authToken = 'ACCOUNT TOKEN';
//require the Twilio module and create a REST client
var client = require('twilio')(accountSid, authToken);
function sendSms(callback) {
client.messages.create({
to: 'TO',
from: 'FROM',
body: 'Message sent from Twilio!',
}, callback);
}
// Export this function as a node module so that you can require it elsewhere
module.exports = sendSms;
Here is a good start for Express.
server.js:
var express = require('express');
var app = express();
// Requiring that function that you exported
var twilio = require('/path/to/twilio.js');
// Creating a controller for the get request: localhost:8081/send/sms
app.get('/send/sms', function (req, res) {
twilio(function(err, message) {
if (err) res.send(err);
res.send('Message sent: ' + message);
});
});
// Creating an HTTP server that listens on port 8081 (localhost:8081)
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
Then you can run node server.js, go to your browser and go to the url: localhost:8081/send/sms and your message will be sent :)
I'd make it so the client sends a HTTP POST request to the server, and then the server will send the message on behalf of the client.
Easiest way is to use express. I'm a bit unsure of how you're serving your website from a Node.js app without using express. Do you have a custom solution or only a non-connected from end, or something like heroku or something? In any case, you can create a route that processes posts with the following:
app.post("send_twilio_message_route", function(req,res){
// this receives the post request -- process here
});
^ Note that doesn't actually create the express app. See my link below and they give examples of some of the nitty gritty and syntax.
So the above would be on the server, in your Node.js app. From the front-end client code that runs in the browser, you need to create a post. The easiest way and most likely way to do it is through $.post in Jquery. if you are using Angular there's a slightly different syntax but it's the same idea. You call post, point it to a url, and put in the body data.
Make the body of the post request contain data such the message, phone numbers,
authentication token maybe.
See this to be able to get the body from a post request and some more implementation details of how to set it up:
How to retrieve POST query parameters?
Depending on the nature of what you're doing you might consider having the sms processing stuff run separate from the actual web service. I would create the sms unique stuff as its own module and have a function retrieve the router so that you can mount is onto the app and move it about later. This might be overkill if you're doing something small, but I'm basically encouraging you to at the start put thought into isolating your services of your website, else you will create a mess. That being said, if it's just a small thing and just for you it might not matter. Depends on your needs.
Important: I highly encourage you to think about the malicious user aka me. If you don't add any authentication in the post body (or you could include it in the url but I wouldn't do that although it's equivalent), a malicious client could totally be a jerk and expend all of your twilio resources. So once you get it basic up in running, before deploying it to anything that people will see it, I recommend you add authentication and rate limiting.

Socketio - Changing data sent on connection

I'm trying to send userid from client side to server via socket io query string on the fly:
var socketio = io.connect(8080, {query : 'userid=100'});
And on server side, I use this id for authentication.
However, I'm a little worried about this. I thought that some malicious users may change userid and send to server their own id.
Am I thinking right? What should I do in this case?

Categories

Resources