Teach you to write a Web remote control gadget

Source: Internet
Author: User

Convention first

Lying in bed at night, found that forget to shut the computer, and do not want to get up, to use mobile phone control computer, Baidu, a lot of. Ha, why I do not myself also realize a, arbitrary DIY. Just do it.

If you do not want to see how to achieve, then directly with the following bar:

Web-controlled: http://smallyard.cn/jobhub/

Control-side JAR package: Http://files.cnblogs.com/files/smallyard/jobhub-client.rar

Run: Java-jar Joghub-client.jar [Your password]

One, network communication

Network communication module, if you do, it is not very difficult, is done, need to buy a server to deploy, this or forget it, in order to play a play and spend money, this kind of thing or do not do, it is good with a third party.

When surfing the Internet, I stumbled upon a cloud bar that provides services for sending messages and subscribing to messages. We just need to use it to connect our control-side web and client listeners together.

It has the Java and JavaScript APIs.

Then think of Baidu's product has an API store, search the next, sure enough to find the right interface.

Second, the client

The main task of the client is to accept the command and execute the command, which I execute by invoking the command line.

The command listens and sends classes, primarily the API that calls the Cloud bar.

/** * Task Listener */public class Jobhandler {private static final String App_key = "567392ee4407a3cd028aacf6";    private static mqttasyncclient mqttasyncclient;    private static String listentopic;        static {try {mqttasyncclient = mqttasyncclient.createmqttclient (App_key);        } catch (Exception e) {e.printstacktrace ();        }}/** * Listen start */public static void Start (Final String topic) {listentopic = topic;        Connect ();    Listen (); public static void Publish (String msg) {try {mqttasyncclient.publish (listentopic + App_key, MSG.G Etbytes (), 1, False, NULL, new Imqttactionlistener () {public void OnFailure (Imqtttoken arg0, Throwable arg                1) {System.out.println ("message returned failed");                } public void onsuccess (Imqtttoken arg0) {System.out.println ("message returned successfully");        }            }); } catch (Mqttexception e) {           E.printstacktrace (); }}//connection server private static void connect () {try {mqttasyncclient.connect (new Imqttactionliste                    NER () {public void onsuccess (Imqtttoken arg0) {System.out.println ("Connection server succeeded.");                Subscribe (); } public void OnFailure (Imqtttoken arg0, Throwable arg1) {System.out.println ("Connection Server failed")                ;        }            });        } catch (Mqttexception e) {e.printstacktrace (); }} private static void subscribe () {try {mqttasyncclient.subscribe (listentopic, 1, NULL, new IM Qttactionlistener () {public void onsuccess (Imqtttoken asyncactiontoken) {SYSTEM.OUT.PR                INTLN ("Successful listener theme:" + Stringutils.join (Asyncactiontoken.gettopics (), ",")); } public void OnFailure (Imqtttoken asyncactiontoken, throwable exception) {SysteM.ERR.PRINTLN ("Monitor failed");        }            });        } catch (Exception e) {e.printstacktrace (); }}//Listener message private static void Listen () {Mqttasyncclient.setcallback (new Mqttcallback () {Pub LIC void Connectionlost (Throwable throwable) {} public void messagearrived (String topic, MQTTMESSAG                E message) throws Exception {string cmd = new String (Message.getpayload ());                SYSTEM.OUT.PRINTLN ("Receive command:" + cmd);                Thread thread = new Thread (new Jobexecutor (cmd));            Thread.Start ();    } public void Deliverycomplete (Imqttdeliverytoken imqttdeliverytoken) {}}); }}

The

command executes the class, invokes the command line Execution command, and then calls the Cloud Bar API to send the execution results.

/** * Task Execution */public class Jobexecutor implements Runnable {private String cmd;    Public jobexecutor (String cmd) {this.cmd = cmd;        public void Run () {BufferedReader br = null;            try {Process p = runtime.getruntime (). exec (This.cmd);            br = new BufferedReader (New InputStreamReader (P.getinputstream ()));            String Line;            StringBuilder sb = new StringBuilder ();            while (line = Br.readline ())! = null) {Sb.append (line). append ("\ n");            } System.out.println (Sb.tostring ());        Jobhandler.publish (Sb.tostring ());            } catch (Exception e) {e.printstacktrace ();        Jobhandler.publish ("Failed execution");                } finally {if (BR! = null) {try {br.close ();                } catch (Exception e) {e.printstacktrace (); }            }        }    }}
Third, web-side

The main task of the web side is to send commands and accept the results of the command execution.

var hasconnect = False;var Appkey = "567392ee4407a3cd028aacf6"; var Yunba = new Yunba ({server: ' Sock.yunba.io ', port:3000,            Appkey:appkey});//Connect server and send Message function connect (cmd, topic) {Yunba.init (function (Success) {if (success) {  Connection Server Yunba.connect_by_customid (' Jobhub-web ', function (Success, MSG, SessionID) {if (success)                    {Hasconnect = true;                    Console.log (' You have successfully connected to the messaging server, session ID: ' + sessionid ');                        Listen for callback message yunba.subscribe ({' topic ': Topic + Appkey}, Function (Success, MSG) {                            if (success) {Console.log (' You have successfully subscribed to channels ' + topic + appkey);                            YUNBA.SET_MESSAGE_CB (SHOWMSG);                        Send (cmd, topic);                        } else {Console.log (msg);                }                    }); } else {conSole.log (msg);        }            }); }    });} Send Message function Send (cmd, topic) {yunba.publish ({' topic ': topic, ' msg ': cmd}, Function (Success, MSG) {if (        Success) {Console.log (' message published successfully ');        } else {Console.log (msg); }    });}    Displays the callback message function showmsg (data) {var msg = data.msg;    Console.log (' Topic: ' + data.topic + ', msg: ' + msg ');    Replace the Enter msg = Msg.replace (/\r\n|\n/g, "<br/>"); Replace execution failed msg = Msg.replace ("Execution failed", "<span style= ' color:red; ')    > Execution Failure </span> ");    Show var $DIVMSG = $ ("#div_msg");    $DIVMSG. Append ("<p>" + msg + "</p>"); Scroll to the bottom $divMsg. scrolltop ($DIVMSG [0].scrollheight);}    $ ("#btnSubmit"). Click (function () {var $INPUTCMD = $ ("#inputCmd");    var $inputTopic = $ ("#inputTopic");    var $spanInfo = $ ("#spanInfo");    var cmd = $inputCmd. val ();    var topic = $inputTopic. val ();        if (!cmd) {$spanInfo. Text ("Command cannot be empty");    Return } if (!topic) {$spanInfo. Text ("Password cannot be null");    Return    } if (Hasconnect) {Send (cmd, topic);    } else {Connect (cmd, topic)} $INPUTCMD. val (""). focus ();    $inputTopic. Val (""); $spanInfo. Text ("Sent command:" + cmd);});    /Bind carriage return event $ (document). KeyDown (function (e) {if (e.keycode==13) {$ ("#btnSubmit"). Click (); }});

  

Iv. Summary

Thinking very complex, in fact, the implementation is very simple.

Source published on GitHub:

Https://github.com/smallyard/smallyard

Https://github.com/smallyard/jobhub-client

Everyone can take their own and expand into their favorite remote control.

Teach you to write a Web remote control gadget

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.