Sockets in android to check real time data change - java

I have to monitor server at real time. Means if there is any change happens in server value need to display it in android device . I have code to implement the same in web browser using html java script .
<script language="javascript" type="text/javascript">
function webservice_connect() {
// open a web socket
hostname = window.location.hostname;
ws = new WebSocket('ws://'+hostname+':8000/echo');
ws.onopen = function()
{
console.log("connected to server");
}
ws.onmessage = function (evt)
{
var received_msg = evt.data;
//alert("Message is received...");
console.log("Message is received..."+received_msg);
rdata = JSON.parse(received_msg);
show_status(rdata);
};
ws.onclose = function()
{
// websocket is closed.
console.log("disconnected server!");
};
}</script>
How can I implements the same in android

You could try using an android webview with exactly the same html/js code.

Related

How to create a web service in Java that keeps push video binary data to a web page?

I have been doing researches on how to real-time stream video from a camera using Java and OpenCV. I could real-time stream the video with Java JFrame application.
Now I want to real-time stream the video on a web page. I have done researches on that. It seems that using <video> tag of HTML5 with src="blob:http://domain.name/codeabcxxxxx" is a good option.
So I've created a web service with Spring MVC framework. Below is the web service controller that handles the AJAX requests, captures the video frames from the camera and sends the AJAX response with the video frames in binary data.
import ...;
#RestController
public class GreetingController {
final static int CV_CAP_DSHOW = 700;
final static int CAMERA_ID = 0;
VideoCapture videoCapture;
Mat m;
public GreetingController() {
System.load( "C:\\opencv\\build\\java\\x64\\" + Core.NATIVE_LIBRARY_NAME + ".dll");
videoCapture = new VideoCapture(CAMERA_ID, CV_CAP_DSHOW);
m = new Mat();
videoCapture.read(m);
}
#GetMapping("/streaming")
public byte[] streaming() {
while (true) {
if (videoCapture.isOpened() && videoCapture.read(m)) {
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( m.channels() > 1 ) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
BufferedImage image = new BufferedImage(m.width(), m.height(), type);
WritableRaster raster = image.getRaster();
DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
final byte[] targetPixels = dataBuffer.getData();
m.get(0, 0, targetPixels);
return targetPixels;
}
}
}
}
Besides that, I've created an index.html web page as following.
<!DOCTYPE html>
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<video id="second-video" controls autoplay muted></video>
<video id="third-video" controls autoplay muted></video>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
const secondVideo = document.getElementById("second-video");
const thirdVideo = document.getElementById("third-video");
const url = "http://localhost:8080/streaming";
axios.get(url).then(res => {
const content = res.data;
// Try URL.createObjectURL
const url = URL.createObjectURL(new Blob([content], {type: "video/H264"}));
secondVideo.src = url;
// Try MediaSource
const mediaSourceA = new MediaSource(url);
thirdVideo.srcObject = mediaSourceA ;
});
</script>
</html>
The client (JavaScript on the web page) sends AJAX request to the web service, after getting AJAX response, containing the video frame in binary data, from the web service, it creates an blob object and add the object to the src attribute of the <video> tag. I have tried to use URL.createObjectURL and MediaSource for two different <video> tags. Nothing works!
Result: No video showing in the <video> tags and the web service does not keep sending next video frames, due to the return statement inside the while-loop.
I miss the following knowledge:
Does the client need to keep sending AJAX requests to the web service for each video frame continuously?
or
The client sends only one AJAX request and the web service keeps sending responses with new video frames continuously?
If the client needs to keep sending AJAX requests, how does the client do that?
If the client needs to send only one AJAX request, how can the web service keeps sending responses continuously? Because with my code above, the while-loop stops due to the return statement and the streaming() method needs to use the return statement.
I kind of miss some understanding, please help me! Thanks!

Javascript: Disable button based on server status

I'm very new to Javascript and I have a button that need to be constantly checked against whether a server is active or not.
I'm using the Play framework based in Java. I already have a class ServerStatus that returns whether a service is healthy or not but I am not sure how to link this into my page which contains the button.
Basically, what I want is that if the server goes down then I want the button disabled so that the user cannot use it while the server is unavailable.
I looked a bit at Websockets and that looks really complex. I wasn't sure if there is a simpler way.
EDIT
Using Websockets: I had a read around and it seems I need to use the onmessage event. I found some sample code but I am not sure how to put this into my (document).ready function.
Below I have some code:
$(document).ready(function(){
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
var chatSocket = new WS("routes");//This does not seem to accept any #routes
var lastState = 'unknown';
chatSocket.onmessage = function(e){
var server_message = e.data;
//do something here about enabling and disabling
console.log(server_message);
}
});
function disable()
{
//disable all buttons
}
function enable()
{
//enable all buttons
}
I am lost as to how to add the websocket here.
I am borrowing heavy from this similar question and answer
The basic code is here:
var isNotWorking = false;
var myFunc = function(){
$.ajax({url: "YOUR_URL_HERE",
type: "HEAD",
timeout:1000,
statusCode: {
200: function (response) {
//alert('Working!');
isNotWorking =false;
},
400: function (response) {
//alert('Not working!');
isNotWorking = true;
},
0: function (response) {
//alert('Not working!');
isNotWorking = true;
}
}
});
$('#mybutton').prop('disabled', isNotWorking);
doSetTimeOut();
}
var doSetTimeOut = function(){
setTimeout(function(){
myFunc();
}, 1000);
}
doSetTimeOut();
See a working JS fiddle here

Grails atmosphere plugin browser hang after few requests

Using atmosphere plugin in grails, after a few requests to server (after few pages of navigation) the browser is not rendering any pages and it is just loading. Other browser in other systems works fine. The code to connect to the server is placed in common layout page.
server code:
def onRequest = { event ->
def userBroadcasters= ServletContextHolder.servletContext.getAttribute('userBroadcasters')
def uid=event.getRequest().session.user?.id
if(!userBroadcasters){
userBroadcasters=[:]
}
Broadcaster privateChannel = BroadcasterFactory.getDefault().lookup("/userChannel"+uid, true);
privateChannel.addAtmosphereResource(event)
userBroadcasters.put(uid,privateChannel)
ServletContextHolder.servletContext.setAttribute('userBroadcasters',userBroadcasters)
event.suspend()
//println ServletContextHolder.servletContext.getAttribute('userBroadcasters')
//println "Inside onRequest!"
}
client code in common layout:
function callback(response) {
if (response.status == 200 && response.responseBody.length > 0) {
//action
}
}
var location = '${request.contextPath}/atmosphere/mx';
var request = {transport: "streaming", fallbackTransport: 'long-polling', contentType: "application/json",connectTimeout:4000};
$.atmosphere.subscribe(location, callback, request);

Firefox, websockets and odd behaviours

Background:
Using WebSockets with JavaScript + Play! framework (2.2).
Can send and receive data fine in Chrome.
Can only receive data (from server) in Firefox as send() doesn't trigger any callbacks.
In addition to the send issue, and in Firefox only again, the tab for the page is always stuck on "connecting" while the spinner keeps spinning (see figure 1).
Misbehaving Browser:
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0)(Firefox 24.0)
(Figure 1. Firefox tab after page has loaded and data is shown)
Any time I refresh the web page, I receive the error below, attributed to the constant page loading behaviour I'm sure.
The connection to ws://localhost:9000/ was interrupted while the page was loading.
The entire JavaScript code:
$(function() {
var chatSocket = new WebSocket("#routes.Application.getMetaData().webSocketURL(request)");
var sendMessage = function() {
chatSocket.send(JSON.stringify({
id: "unique",
name: "a name",
age: 22
}));
}
var receiveEvent = function(event) {
var data = JSON.parse(event.data)
document.write(data.age);
document.write(data.name);
document.write(data.message);
document.write("\n");
sendMessage();
chatSocket.close();
}
chatSocket.onmessage = receiveEvent
})
Now In the past, I've been trying with MozWebSocket instead of the standard WebSocket, but I get nothing rendered on screen using that module therefore unless there is an angle I've missed, WebSocket is the better one to use.
The relevant Play! block:
public static WebSocket<JsonNode> getMetaData() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {
// For each event received on the socket,
in.onMessage(new Callback<JsonNode>() {
#Override
public void invoke(JsonNode jsonNode) {
System.out.println("Message Incoming!");
System.out.println(jsonNode.get("id"));
System.out.println(jsonNode.get("name"));
System.out.println(jsonNode.get("age"));
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
System.out.println("Disconnected");
}
});
ObjectNode node = Json.newObject();
node.put("message", "hello");
node.put("name", "client");
node.put("age", 1);
out.write(node);
//same result commented/uncommented
out.close();
}
};
}
So in Chrome, the flow would be:
document.write(...)
"Message Incoming!"
... JSON attributes
"Disconnected"
But in Firefox, the flow is:
document.write(...)
"Disconnected"
Any help in diagnosing these problems would be greatly appreciated. I have no intention of supporting IE, but having both Mozilla and Chrome working would be great.
Other JavaScript Warnings:
Below is a warning I occasionally get in Firefox's console while pointing at the "ws" protocol as the culprit. What its relevance is to my problem, I do not know.
Use of getPreventDefault() is deprecated. Use defaultPrevented instead.
You call document.write() after the document is loaded, which then implies document.open() which in turn replaces the document and by that unloads the old one and aborts stuff like timeouts or websockets.
Use something other than document.write() and you should be fine.

facebook login Server-side Apps with javascript sdk

I have searched stackoverflow for an full example or some blog that explains how to make facebook login Server-side Apps with javascript sdk
but didn't find anything.
I have searched developer.facebook.com site and the only thing i have got was a php example https://developers.facebook.com/docs/howtos/login/server-side-login/.
The problem is that i must use JavaScript.
Why should i want to do that?
The reason is that i want to upload files to the server(google-app-engine(Java Sdk)) and save them on the db with the facebook user id and retrieve them by his user id.
another question is, how can i debug my javascript code if he uploaded dynamically?what about code assist?
Well I can help you with this issue. If you need to use the JS SDK of FB, then you have to do everything on the client side or on browser, because Facebook doesn't have any support for Java on Server Side.
So I suggest you that you can authenticate user on client, define your scopes for accessing user profile, once authenticated by user you will get response as JSON Object which you can send using ajax to AppEngine Backend.
I am sharing my link where I used FB Login and accessing User's Profile Information along with his photos in albums and videos.
http://demositeunicfyp.appspot.com/fb-pictures.html
http://demositeunicfyp.appspot.com/facebook.html
You can Debug the JS Code in your browser to see what kind of response object you are getting back from Facebook APIs.
$(document).ready(function() {
// Initializing the Facebook SDK
FB.init({
appId : 'XXXXXXXXXXXXXXXX',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
// Method to check if a user is looged in to FB or Not
FB.getLoginStatus(updateButton);
$("#logout").live("click", function(event) {
event.preventDefault();
// FB.getLoginStatus(updateButton);
FB.logout(function(response) {
$("#loginDiv").show();
$("#logoutDiv").hide();
});
});
$("#fbLoginButton").live("click", function(event) {
//event.preventDefault();
FB.getLoginStatus(updateButton);
});
function updateButton(response) {
var button = document.getElementById("fbLoginButton");
if (response.authResponse) {
// user is already logged in and connected
// button.innerHTML = 'Facebook Logout';
//$("#loginDiv").hide();
//$("#logoutDiv").show();
//window.location = '/confirm';
FB.api('/me', function(response) {
$("#userName").text(response.name);
$("#userEmail").text(response.email);
});
} else {
// user is not connected to your app or logged out
// button.innerHTML = 'Facebook Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
// button.innerHTML = 'Facebook Logout';
$("#loginDiv").hide();
$("#logoutDiv").show();
FB.api('/me', function(response) {
$("#userName").text(response.name);
$("#userEmail").text(response.email);
});
} else {
//user cancelled login or did not grant authorization hence do nothing
}
}, {
scope : 'email,publish_actions'
});
}
}
}
});
Taken from JS.php in SDK download
<?php
require '../folderTo/facebook.php';
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('me?fields=photos'); } catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
Working example here: http://slicethegreen.com/examples/js.php

Categories