GAE Channel Api vs Socket - javascript

I have a Google app that runs using GO on the server side and Javascript on the client side. The client generate every certain timestep a javascript object (that could be "stringified") that needs to be sent back to the server and saved as json file. Based on the google app engine documentation it seems that this could achieved with both:
channel api
socket service
but I couldn't find any examples for both of these and also it is not clear to me which one is the best to accomplish the goal. Can anyone help me?
Thanks a lot.

Maybe this could be useful to someone so here is the way I did that:
saveData : function saveData() {
var _this = this,
save = this.shadowRoot.querySelector('#save-data'),
subData = JSON.stringify(_this.app.userSession);
save.url="url";
save.body = subData;
save.go();
}

Related

Posting Variable Values from Javascript and Reading them with Python (UV4L, WebRTC, Raspberrypi3)

I am working on a project where we plan on controlling a rover through a web-based application. I am using UV4L and its modules on the Raspberry Pi. I have the streaming side set up well, but now I am trying to send data back to the Pi.
I have taken this joystick and put into the demo webpage.
What I want to do is take the X and Y value that this joystick produces and send it back to the Pi and have it print the values. The way I have been attempting to do this is to turn the X and Y values into a JSON and read the JSON with Python. I am relatively new to programming, and have been thrown into the proverbial deep end.
I was trying to use an example I found in another stackoverflow question this is what I produced butchering the code:
var xhr = new XMLHttpRequest();
var url= “webappurl”;
xhr.open(“POST”, url, true);
xhr.setRequestHeader(“Content-Type”, “json”);
xhr.onload= function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json =JSON.parse(xhr.responseText);
console.log(json.x +”, “ + json.y);
}
};
var data = JSON.stringify({x, y});
xhr.send(data);
Then I did this on the Python Side:
import requests
import simplejson
r = requests.get('webappurl')
c = r.content
j = simplejson.loads(c)
print(j)
The problem I have been having is that everything I find online has a different recommendation on how to do this and I haven't been able to find something in other people's projects I could utilise for our purposes or have the knowledge to adapt, and I need to keep it as direct/simple as possible.
I am under the impression that the joystick may already be built with functions/variables that can be used to trigger or post.
Any recommendations for the best way to go about this or the correct code to do this would be appreciated - I also have the WebRTC data channels available but I don't know if I need to use them to do this.
I also wondered if there was means to send the variable values over the websocket and use python to parse the websocket.
Thank you for your time,
Since you are developing a web application, it seems natural to stay with WebRTC. UV4L supports two-way audio, video and data channels. Here is how data channels work on the UV4L side.
Furthermore, the built-in WebRTC demo page that you can fetch, as an example, from the /stream/webrtc URL on the uv4l server certainly embeds some javascript code using data channels from the client side. You can find some code in this other demo web app here as well.

Display Kafka messages on web page

I have a Java Spring Application with a Tomcat server that listen on kafka topic. I want to display all messages in a real-time mode on the web page. Therefore, when a kafka messages is arrived in the backend I want to see it on my web page. I don't know a good approach to push kafka message directly to the front-end and display it on web page. Is someone could help my with a solution and some examples that could help? Thanks!
I have implemented a system like this in Java for my last employer, albeit not with Spring/Tomcat. It was consuming messages from Kafka and serving them on a web socket to be displayed in the browser. The approach I followed was to use akka-stream-kafka and akka-http for web-socket support. The benefit of that is both are based on akka-streams which makes it an easy fit for streaming data.
While you can embed akka-http in your spring app running inside tomcat, it may not feel the most natural choice any more as spring framework already has its own support for both kafka and websockets. However, if you're not familiar with either, then jumping on the akka approach may be easiest and the core logic goes along these lines (I can't share the code from work so have just put this together from the examples in the docs, not tested):
public Route createRoute(ActorSystem system) {
return path("ws", () -> {
ConsumerSettings<byte[], String> consumerSettings = ConsumerSettings.create(system, new ByteArrayDeserializer(), new StringDeserializer())
.withBootstrapServers("localhost:9092")
.withGroupId(UUID.randomUUID().toString()) //this is so that each client gets all messages. To be able to resume from where a client left off in case of disconnects, you can generate in on the client side and pass in the request
.withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")
return handleWebSocketMessages(
Flow.fromSinkAndSourceCoupled(
Sink.ignore(),
Consumer.committableSource(consumerSettings, Subscriptions.topics("topic1"))
.map(msg -> TextMessage.create(msg.record().value()))
)
);
}
}
To expose this route you can follow the minimalistic example, the only difference being the route you define needs the ActorSystem:
final Http http = Http.get(system);
final ActorMaterializer materializer = ActorMaterializer.create(system);
final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = createRoute(system).flow(system, materializer);
final CompletionStage<ServerBinding> binding = http.bindAndHandle(routeFlow,
ConnectHttp.toHost("localhost", 8080), materializer);
Once you have your messages published to the websocket, the front end will code will of course depend on your UI framework of choice, the simplest code to consume ws messages from javascript is:
this.connection = new WebSocket('ws://url-to-your-ws-endpoint');
this.connection.onmessage = evt => {
// display the message
To easily display the message in the UI, you want the format to be something convenient, like JSON. If your Kafka messages are not JSON already, that's where the Deserializers in the first snippet come in, you can convert it to a convenient JSON string in the Deserializer or do it later on in the .map() called on the Source object.
Alternatively, if polling is an option you can also consider using the off-the-shelf Kafka Rest Proxy, then you only need to build the front-end.

json refresh no ajax ,websockets

I want to get the data from here
https://btc-e.com/api/3/ticker/btc_usd
in php i use :
$jsonbtce = file_get_contents('https://btc-e.com/api/3/ticker/btc_usd');
$decodedbtce = json_decode($jsonbtce);
$lastprice = $decodedbtce->btc_usd->last;
then i use jquery ajax to refresh the data
var updateInterval = setInterval(function() {
$('.mydivclass').load('btce.php');
},3*1000);
How can i use websockets with jquery or javascript to get the data from that url ? so i can use the $lastprice for other stuff even if price updates,using ajax not good.
I'm facing the same problem as you. I'm sorry to say that you will need to set up a WebSocket server (written in PHP or Java, for example) and configure it. Take a look at Ratchet ws server, node.js webSocket servers or search through GitHub for a webSocket server.
This is the info I have.
I will be glad if someone posts a more specific answer.
This looks very nice, if you know Java.

What's the most efficient way to call a Node.js backend function with JavaScript

I'm an html5 developer with mainly JavaScript experience. I'm starting to learn the backend using Node.js. I don't have a particular example of this question/requirements. I'd like to call a back end function with JavaScript, but I'm not sure how. I already researched events and such for Node.js, but I'm still not sure how to use them.
Communicating with node.js is like communicating with any other server side technology.. you would need to set up some form of api. What kind you need would depend on your use case. This would be a different topic but a hint would be if you need persistent connections go with web sockets and if you just need occasional connections go with rest. Here is an example of calling a node function using a rest api and express.
var express = require('express');
var app = express();
app.post('/api/foo', foo);
function foo(req, res){
res.send('hello world');
};
app.listen(3000);
From the frontend you can post to this REST endpoint like so.
$.post("/api/foo", function(data) {
console.log( "Foo function result:", data );
});
If you're just starting with node-js, don't worry about Websockets just yet.
You're going to want to create a REST API (most likely) depending on what you're trying to accomplish. You can put that REST API behind some kind of authentication if desired.
A REST API is going to have endpoints for creating/deleting/updating and getting (finding) a document, like a given user.
My recommendation is to work backwards from something that's already working. Clone this app locally and check out the controllers to see examples of how this application interacts with creating users.
https://github.com/sahat/hackathon-starter
Once you create a controller that returns data when a client hits an endpoint (like http://localhost:3000/user/create ) , you'll want to create some HTML that will interact with endpoint through a form HTML element. Or you can interact with that endpoint with Javascript using a library like jQuery.
Let me know if that makes sense to you. Definitely a good starting point is to clone that app and work backwards from there.
Can I suggest trying api-mount. It basically allows calling API as simple functions without having to think about AJAX requests, fetch, express, etc. Basically in server you do:
const ApiMount = apiMountFactory()
ApiMount.exposeApi(api)
"api" is basically an object of methods/functions that you are willing to call from your web application.
On the web application you then do this:
const api = mountApi({baseUrl: 'http://your-server.com:3000'})
Having done that you can call your API simply like this:
const result = await api.yourApiMethod()
Try it out. Hope it helps.

PHP minimal working example of Web Sockets

I'm trying to determine how to setup a web socket for the first time ever so a working minimal example with static variables (IP address for example instead of getservbyname) will help me understand what is flowing where.
I want to do this the right way so no frameworks or addons for both the client and the server. I want to use PHP's native web sockets as described here though without over-complicating things with in-depth classes...
http://www.php.net/manual/en/intro.sockets.php
I've already put together some basic JavaScript...
window.onload = function(e)
{
if ('WebSocket' in window)
{
var socket = new WebSocket('ws://'+path.split('http://')[1]+'mail/');
socket.onopen = function () {alert('Web Socket: connected.');}
socket.onmessage = function (event) {alert('Web Socket: '+event.data);}
}
}
It's the PHP part that I'm not really sure about. Presuming we have a blank PHP file...
If necessary how do I determine if my server's PHP install has this socket functionality already available?
Is the request essentially handled as a GET or POST request in
example?
Do I need to worry about the port numbers? e.g. if
($_SERVER['SERVER_PORT']=='8080')
How do I return a basic message on the initial connection?
How do I return a basic message say, five seconds later?
It's not that simple to create a simple example, I'm afraid.
First of all you need to check in php configuration if the server is configured for sockets with the setting enable-sockets
Then you need to implement (or find) a websocket server that at least follows the Hybi10 specification (https://datatracker.ietf.org/doc/html/draft-ietf-hybi-thewebsocketprotocol-10) of websockets. If you find the "magic number" 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 in the code for the header, you can be sure it does follow at least Hybi06 ...
Finally, you need to have access to an admin console on the server in order to execute the PHP websocket server using php -q server.php
EDIT: This is the one I've been using a year ago ... it might still work as expected with current browsers supporting Websockets: http://code.google.com/p/phpwebsocket/source/browse/trunk/+phpwebsocket/?r=5

Categories