Adobe Air communication with cmd - actionscript-3

Is there a way to communicate with cmd (using native process) in adobe air.
As an example;
How to send "ping www.google.com" to cmd and capture the return values in Air.
Edit
Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Program Files\Adobe\Adobe Flash Builder 4.5>ping www.google.com
Pinging www.l.google.com [209.85.175.103] with 32 bytes of data:
Reply from 209.85.175.103: bytes=32 time=1733ms TTL=50
Reply from 209.85.175.103: bytes=32 time=189ms TTL=50
Reply from 209.85.175.103: bytes=32 time=188ms TTL=50
Reply from 209.85.175.103: bytes=32 time=186ms TTL=50
Ping statistics for 209.85.175.103:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 186ms, Maximum = 1733ms, Average = 574ms
C:\Program Files\Adobe\Adobe Flash Builder 4.5>
I can print above from Air application. I need to know is there a specific way to grab the values of Minimum = ?, Maximum = ? and Average = ?
Planning to explode the string. Is there another way. Please help me
Thanks in advance.

You should read up on Interacting with Native Processes in AIR. What you write in the command prompt (ping in your case) is another exe file located in a folder specified in the Windows Path. So you'll actually have to invoke the ping.exe with the NativeProcess class in AIR. OR, you could study how the exe works and then implement that logic in your AIR application.
EDIT
After you have edited your question, here are more details:
You use Regular Expressions (follow that link and learn about regular expressions)
Since you want to match this pattern
Minimum = (number)ms, Maximum = (number)ms, Average = (number)ms
your regular expression will look something like
var r:RegExp=/Minimum = ([\d\.]+)ms\, Maximum = ([\d\.]+)ms\, Average = ([\d\.]+)ms/i;
//Then, you execute this on your result string
var arr:Array=r.exec(result);
//Then check if the result matched your regex
if(arr != null) {
var min:int=arr[1];
var max:int=arr[2];
var avg:int=arr[3];
} else {
trace("invalid result from ping");
}

To execute shell command (e.g. ping,) you either need to run cmd.exe from it's location or run ping.exe. I found no direct way to execute shell commands in AIR, and execution of bat files is prohibited too. So, to call cmd.exe you need to know where it is. It's location given by environment variable %ComSpec% (I'm assuming we're talking about Windows,) but you can't get this value from AIR application too.
So, when I solved such a problem, I just bundled cmd.exe with my native AIR app. Not the best solution, because cmd.exe is taken on another OS. You can solve your problem this way:
create native helper exe which executes 'echo %ComSpec%' and exits. You can use system() command to do that, see WinApi docs.
in AIR app, run this helper and read console output.
invoke cmd.exe using this path (you can specify /C argument for single commands.)
Or, if you prefer, create native exe which gets arguments from AIR app and executes them on the shell with system(). AIR app can then read console output from this exe. Less job for ActionScript, more for C++ (or whatever you use for native helper.)
Update:
If you already got ping output, just parse it with RegExp's, like
"Reply from \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}: bytes=32 time=(\d{1,})ms TTL=\d{1,}". Convert captured time string to int, then calculate min/max/averages.

Related

Streaming a virtual terminal without video

If I want to live broadcast some work on a text editor embedded in a virtual terminal on my personnal computer, I can stream on the web a video of the window containing it.
But since information consists mainly in a bunch of characters, possibly with some colors and formating, I think that video is a waste of ressources, bandwidth and technology speaking.
What would you recommend for this, and is there some server implementing the solution somewhere ?
The requirements are :
the stream must be almost real time (at least 1 update per second and no more than 1 second delay)
audience can access the stream with only a web browser (no additional software on their side), read-only (no interaction with the stream or with my terminal)
features from say xterm or urxvt be supported
all necessary software (both streamer client side and potential server side) are open source
Comments on technical advantages of such tool compared to video streaming are welcome.
I finally took the time to implement a complete solution, using socket.io within a simple NodeJS server for broadcasting.
On the client side, serve a simple HTML with an Xterm.js terminal
<script src='/socket.io/socket.io.js'></script>
<script src="xterm/xterm.js"></script>
...
<div class="terminal" id="terminal"></div>
and script the synchronization along the lines of
var socket = io();
term.open(document.getElementById('terminal'));
var updateTerminal = socket.on("updateTerminal", function(data) {
term.write(data);
});
Now the data that can be passed to term.write of Xterm.js can be raw terminal data. Several UNIX utilities can monitor such raw data from a terminal, for instance tmux as proposed by jerch in the comments, or script.
To pass these data to the server for broadcasting, the easiest way is to use a named pipe; so on the server side
mkfifo server_pipe
script -f server_pipe
(the terminal issuing that last command will be the one broadcasting; if one does not have physical access to the server, one can use an additional pipe and a tunneling connection
mkfifo local_pipe
cat local_pipe | ssh <server> 'cat > path/to/server_pipe'&
script -f local_pipe
)
Finally, the NodeJS server must be listening to the named pipe and broadcast any new data
/* create server */
const http = require('http');
const server = http.createServer(function (request, response) {
...
});
/* open named pipe for reading */
const fs = require('fs');
const fd = fs.openSync("path/to/server_pipe", 'r+')
const termStream = fs.createReadStream(null, {fd});
termStream.setEncoding('utf8');
/* broadcast any new data with socket.io */
const iolib = require("socket.io");
io = iolib(server);
termStream.on('data', function(data) {
io.emit("updateTerminal", data)
});
All this mechanism is implemented in my software Remote lecture.
As for the comparison with video broadcast, I did not take the time to actually quantify the difference, but for equivalent resolution and latency, the above mechanism should use much less network and computing resources than capturing a graphic terminal output and sharing it with video.

How can I monitor my Chrome App's process in Windows

I am trying to use an external process monitoring tool to alert me when my Chrome App dies. Unfortunately, all Chrome Apps seem to run inside their own chrome.exe process so there's no way to differentiate them in the monitoring tool. Is there any way to see which Chrome App is running in which process?
While this certainly is a manual solution (i.e. you won't be able to easily feed it into other tools), Chrome's built-in Task Manager (accessible via menu or Shift+Esc) allows you to correlate task (in this case, the App) to the system Process ID.
Whether it's possible from "outside" or using a command line call is still an open question.
One thing that can help distinguishing the process is that app processes always launch with --extension-process command line switch. But that doesn't allow you to tell which app (or extension) it is.
It's possible that if verbose enough logging is enabled, one would be able to parse the proccess ID from the logs.
I was finally able to do this using tasklist and looking for the window title which is set from the app name in manifest.json:
tasklist /FI "WINDOWTITLE eq MyChromeAppName" | find "chrome.exe"
For the purposes of the monitor, I wrapped it in a node.js function that the monitor app could use:
function chromeAppIsRunning(appName, cb){
var cmd = 'tasklist /FI "WINDOWTITLE eq ' + appName + '" | find "chrome.exe"';
childprocess.exec(cmd, function(err, stdout, stderr) {
stdout = (stdout || '').toLowerCase();
cb(stdout.indexOf('chrome.exe') > -1);
});
};
Then you can use it like this:
chromeAppIsRunning('MyApp', function(exists){
console.log('MyApp is running:', exists);
});
Hope that helps someone else

Extracting the outputs/results from an executed .pexe file

My goal is to convert a C++ program in to a .pexe file in order to execute it later on a remote computer. The .pexe file will contain some mathematical formulas or functions to be calculated on a remote computer, so I’ll be basically using the computational power of the remote computer. For all this I’ll be using the nacl_sdk with the Pepper library and I will be grateful if someone could clarify some things for me:
Is it possible to save the outputs of the executed .pexe file on the remote computer in to a file, if it’s possible then how? Which file formats are supported?
Is it possible to send the outputs of the executed .pexe file on the remote computer automatically to the host computer, if it’s possible then how?
Do I have to install anything for that to work on the remote computer?
Any suggestion will be appreciated.
From what I've tried it seems like you can't capture the stuff that your pexe writes to stdout - it just goes to the stdout of the browser (it took me hours to realize that it does go somewhere - I followed a bad tutorial that had me believe the pexes stdout was going to be posted to the javascript side and was wondering why it "did nothing").
I currently work on porting my stuff to .pexe also, and it turned out to be quite simple, but that has to do with the way I write my programs:
I write my (C++) programs such that all code-parts read inputs only from an std::istream object and write their outputs to some std::ostream object. Then I just pass std::cin and std::cout to the top-level call and can use the program interactively in the shell. But then I can easily swap out the top-level call to use an std::ifstream and std::ofstream to use the program for batch-processing (without pipes from cat and redirecting to files, which can be troublesome under some circumstances).
Since I write my programs like that, I can just implement the message handler like
class foo : public pp::Instance {
... ctor, dtor,...
virtual void HandleMessage(const pp::Var& msg) override {
std::stringstream i, o;
i << msg.AsString();
toplevelCall(i,o);
PostMessage(o.str());
}
};
so the data I get from the browser is put into a stringstream, which the rest of the code can use for inputs. It gets another stringstream where the rest of the code can write its outputs to. And then I just send that output back to the browser. (Downside is you have to wait for the program to finish before you get to see the result - you could derive a class from ostream and have the << operator post to the browser directly... nacl should come with a class that does that - I don't know if it actually does...)
On the html/js side, you can then have a textarea and a pre (which I like to call stdin and stdout ;-) ) and a button which posts the content of the textarea to the pexe - And have an eventhandler that writes the messages from the pexe to the pre like this
<embed id='pnacl' type='application/x-pnacl' src='manifest.nmf' width='0' height='0'/>
<textarea id="stdin">Type your input here...</textarea>
<pre id='stdout' width='80' height='25'></pre>
<script>
var pnacl = document.getElementById('pnacl');
var stdout = document.getElementById('stdout');
var stdin = document.getElementById('stdin');
pnacl.addEventListener('message', function(ev){stdout.textContent += ev.data;});
</script>
<button onclick="pnacl.postMessage(stdin.value);">Submit</button>
Congratulations! Your program now runs in the browser!
I am not through with porting my compilers, but it seems like this would even work for stuff that uses flex & bison (you only have to copy FlexLexer.h to the include directory of the pnacl sdk and ignore the warnings about the "register" storage location specifier :-)
Are you using the .pexe in a browser? That's the usual case.
I recommend using nacl_io to emulate POSIX in the browser (also look at file_io. This will allow you to save files locally, retrieve them, in any format you fancy.
To send the output use the browser's usual capabilities such as XMLHttpRequest. You need PNaCl to talk to JavaScript for this, you may want to look at some of the examples.
A regular web server will do, it really depends on what you're doing.

Which function does OpenAs_RunDLL finally calls under Windows 8?

I'm trying to use OpenAs_RunDLLW to let the user select application he wants to open specific file with. But I don't want to really launch anything, just to let the user select and remember his choise so I can then open the file with this program later. In Windows XP, Vista and 7 OpenAs_RunDLLW finally used to call ShellExecuteExW, so I could temporary put the int 3 opcode at the beginning of this function, catch the exception and get all parameters passed to ShellExecuteExW. This was good and really worked.
But under Windows 8/8.1 it seems that OpenAs_RunDLLW does not call ShellExecuteExW, since the breakpoint is never hit. The selected app is launched instead. So, my question is - which API function does OpenAs_RunDLLW finally call to execute the program under Windows 8?
I believe that the shell now uses IAssocHandler::Invoke to open the item. However, you probably don't really care about that; what you want is a way to find out how to get the invocation handler.
For that, you want ShAssocEnumHandlers, which takes a file name extension and returns an association enumerator (that is, a function that will enumerate all the various applications that can open that extension).
On Windows Vista and later, use SHOpenWithDialog() instead of calling OpenAs_RunDLL(), and then use SHAssocEnumHandlers() to find out which handlers are registered and to invoke a particular handler when needed, instead of using ShellExecute().

Run common TCL script on Windows and Linux

I am new to TCL. How can I run a common tcl script across Windows and Linux? I'd like to check platform type first and then call appropriate tcl proc.
Yup that worked, Jackson. Basically, I wanted to know what OS my script is running on, for example,
set OS [lindex $tcl_platform(os) 0]
if { $OS == "Windows" } {
perform this ...
} else {
perform that ...
}
You can start by looking at the tcl_platform array. On my (windows) machine this reports the following:
% parray tcl_platform
tcl_platform(byteOrder) = littleEndian
tcl_platform(machine) = intel
tcl_platform(os) = Windows NT
tcl_platform(osVersion) = 5.1
tcl_platform(platform) = windows
tcl_platform(threaded) = 1
tcl_platform(tip,268) = 1
tcl_platform(tip,280) = 1
tcl_platform(user) = username
tcl_platform(wordSize) = 4
On a Unix system the os and osVersion will be the values reported by uname -s and uname -r respectivley. If you need something more sophisticated then the platform package may be the way to go!
Most things in Tcl work the same on Windows and Unix; the vast majority of details where there differences are hidden. To handle the rest:
Use file join instead of concatenating with / in between.
Use file nativename to make filenames to hand off to subprocesses.
Be careful with load; what it does is not at all portable.
The info command has some useful things, such as the name of the Tcl interpreter (info nameofexecutable) so you can start up interpreters in subprocesses portably and easily.
Some things just aren't portable (e.g., access to the Windows registry).
There are some subtle differences too, but you'll have to guide us with what you're doing with your program so that we can know what bits matter (e.g., Windows locks executables when they're running while Unix doesn't; sometimes that changes things).