After working for several months, I started to get started with Java at the company, and Android started from scratch.
In order to synchronize with the company's projects as soon as possible, I began to get started with some projects by taking advantage of the basic Android books. I remember that the first step was to build a hands-on Project: remote electronic monitoring based on Android TV, after almost all this is done, I will not proceed. Later, I had to fix bugs and add modules.
I learned about socket recently and found some examples on the Internet, such as the QQ example of the Android mobile phone. I think it is quite interesting. I want to have a good time and have a bit of experience. I will share it with you here.
As a beginner, many areas are stretched out and there are some shortcomings. I hope you can give me more advice. Off
Some basic knowledge of socket is not here. I made a simple small example of some functions of PC controlled by Android mobile phones. I would like to share with you:
The example has the following functions: control the shutdown of your computer on your mobile phone, restart your computer, and obtain screenshots of your computer. First look at the PC server section:
Enable a serversocket on the server:
Code:
Package com. xluo. server;
Import java. Io. objectinputstream;
Import java. Io. objectoutputstream;
Import java.net. inetaddress;
Import java.net. serversocket;
Import java.net. Socket;
Import java. util. date;
Import com. xluo. Common. userdata;
Import com. xluo. Common. usermessage;
Public class startserver {
Public startserver (){
Serversocket SS;
Try {
Ss = new serversocket (5001); // service port number, which can be customized, but must be consistent with the client's Port Request number, and preferably an integer greater than 1024,
System. Out. println ("the server has started at" + new date ());
While (true ){
Socket S = ss. Accept ();
String clientaddr = S. getinetaddress (). tostring ();
System. Out. println (clientaddr );
Objectinputstream OIS = new objectinputstream (S. getinputstream (); // obtain the object in the socket
Userdata UD = (userdata) Ois. readobject (); // gets the object sent from the client. userdata is a custom Java file.
Boolean shutdown = Ud. getshutdown (); // whether the request is shutdown
Boolean restart = Ud. getrestart (); // restart the request
Boolean pshow = Ud. getgetpicture (); // screenshot request
Objectoutputstream OOS = new objectoutputstream (S. getoutputstream (); // obtain the socket output object
Usermessage um = new usermessage (); // pre-return client object
If (shutdown ){
Um. settype (1 );
Oos. writeobject (UM); // send a message to the client
Runtime.getruntime(cmd.exe C ("cmd.exe/C shutdown-S-T 00"); // run the shutdown command on the PC
} Else if (restart ){
Um. settype (1 );
Oos. writeobject (UM );
Runtime.getruntime(cmd.exe C ("cmd.exe/C shutdown-R-T 00"); // restart the command
} Else if (pshow ){
Um. settype (1 );
Um. SETB (copyscreen. getbytefile (); // obtain the screenshot and convert it to the byte [] type and assign it to the Um object.
Oos. writeobject (UM );
}
S. Close ();
}
} Catch (exception e ){
E. printstacktrace ();
}
}
}
One problem that has plagued me for a long time is that the client sends data to the server and reads data in the socket as an object (there are other methods, later, I found that the object class sent by the client must be under the same package name as the class accepted by the server, and the class name must be the same. Now I want to think it is a poor question, but I didn't know at the time. It was just like walking a blind man...
On the server side, you may be interested in the screenshot copyscreen class. The following code is provided:
Package com. xluo. server;
Import java. AWT. dimension;
Import java. AWT. rectangle;
Import java. AWT. Robot;
Import java. AWT. toolkit;
Import java. AWT. image. bufferedimage;
Import java. Io. bytearrayoutputstream;
Import javax. ImageIO. ImageIO;
Public class copyscreen {
Private Static dimension D = toolkit. getdefatooltoolkit (). getscreensize ();
Public copyscreen (){
}
Public static byte [] getbytefile () throws exception {// obtain the binary stream of the screenshot Image
Bufferedimage Bi = NULL;
Bi = (new robot ()). createscreencapture (New rectangle (0, 0, (INT) d. getwidth (), (INT) d. getheight (); // The bufferedimage object of the screenshot.
Bytearrayoutputstream baos = new bytearrayoutputstream ();
ImageIO. Write (Bi, "PNG", baos );
Byte [] B = NULL;
B = baos. tobytearray ();
Return B;
}
}
In fact, it is very easy. First, use the createscreencapture of robot to make an image and convert it to a byte stream.
At this point, the work on the server end has been completed, but some of them may be the same as me and want to know the data object file passed in the socket.
From the above we can see that I have defined two objects for data transmission: 1. userdata. java Server for receiving, 2. usermessage. the Java Server is used for sending. The two files are exactly the same idea on the client, that is, userdata is used for sending, while usermessage is used for receiving
Let's take a look at the two files:
Userdata. Java:
Package com. xluo. Common;
Import java. Io. serializable;
Public class userdata implements serializable {
/**
*
*/
Private Static final long serialversionuid = 1l;
Private Boolean shutdown;
Private Boolean restart;
Private Boolean getpicture;
Public void setshutdown (Boolean BL ){
This. Shutdown = bl;
}
Public Boolean getshutdown (){
Return this. Shutdown;
}
Public void setrestart (Boolean BL ){
This. Restart = bl;
}
Public Boolean getrestart (){
Return this. Restart;
}
Public void setgetpicture (Boolean BL ){
This. getpicture = bl;
}
Public Boolean getgetpicture (){
Return this. getpicture;
}
}
I used to understand it as a mobile database (purely my personal understanding)
Usermessage. Java:
Package com. xluo. Common;
Import java. Io. serializable;
Public class usermessage implements serializable {
/**
*
*/
Private Static final long serialversionuid = 1l;
Private int type;
Private byte [] B; // The byte array used to transmit the image
Public void settype (INT t ){
This. type = T;
}
Public int GetType (){
Return this. type;
}
Public void SETB (byte [] B ){
This. B = B;
}
Public byte [] getb (){
Return this. B;
}
}
Let's take a look at the client:
In fact, the client also draws three buttons on the main interface of an APK, and then shuts down, restarts, and obtains the image request.
The Code is as follows:
Package com. xluo. pcphone;
Import com. xluo. Common. userdata;
Import com. xluo. Common. usermessage;
Import com. xluo. Socket. usersocket;
Import Android. OS. Bundle;
Import Android. OS. Handler;
Import Android. OS. message;
Import Android. App. activity;
Import Android. content. intent;
Import Android. View. Menu;
Import Android. View. menuitem;
Import Android. View. view;
Import Android. View. window;
Import Android. widget. Button;
Import Android. widget. Toast;
Import Android. Support. v4.app. navutils;
Public class mainactivity extends activity implements Android. View. View. onclicklistener {
Private button Bt1, bt2, bt3;
Private userdata UD;
Private handler mhandler = new handler () {// use handler to process the data sent from the thread
Public void handlemessage (Message MSG ){
Switch (msg. What ){
Case 1:
Usermessage um = (usermessage) msg. OBJ;
If (UM. GetType () = 1 & um. getb () = NULL ){
Toast. maketext (mainactivity. This, "Operation successful", Toast. length_short). Show ();
}
Break;
Case 0:
Toast. maketext (mainactivity. This, "failed to connect to the server! ", Toast. length_short). Show ();
Break;
Default:
Break;
}
}
};
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Requestwindowfeature (window. feature_no_title );
Setcontentview (R. layout. activity_main );
Bt1 = (button) findviewbyid (R. Id. Shutdown );
Bt2 = (button) findviewbyid (R. Id. Restart );
Bt3 = (button) findviewbyid (R. Id. spicture );
Bt1.setonclicklistener (this );
Bt2.setonclicklistener (this );
Bt3.setonclicklistener (this );
}
@ Override
Public Boolean oncreateoptionsmenu (menu ){
Getmenuinflater (). Inflate (R. Menu. activity_main, menu );
Return true;
}
Public void onclick (view v ){
// Todo auto-generated method stub
Switch (V. GETID ()){
Case R. Id. Shutdown: // Shutdown Button event
UD = new userdata ();
UD. setshutdown (true );
New usersocket (mhandler, UD). Start (); // start the thread and send the request
Break;
Case R. Id. Restart: // restart button event
UD = new userdata ();
UD. setrestart (true );
New usersocket (mhandler, UD). Start ();
Break;
Case R. Id. spicture: // get image button event
Intent I = new intent ();
I. setclass (this, pictureshow. Class );
Startactivity (I); // jump to the new activity
Break;
}
}
}
There is nothing to talk about in this file. Let's look at the thread started here,
Usersocket. Java:
Package com. xluo. Socket;
Import java. Io. objectinputstream;
Import java. Io. objectoutputstream;
Import java.net. inetsocketaddress;
Import java.net. Socket;
Import com. xluo. Common. userdata;
Import com. xluo. Common. usermessage;
Import Android. OS. Handler;
Import Android. OS. message;
Public class usersocket extends thread {
Private handler mhandler;
Private userdata UD;
Public usersocket (handler H, object ob ){
This. mhandler = H; // handler is required to process the data sent from the server.
This. ud = (userdata) ob; // data object to be sent to the server
}
Public void run (){
Socket S = new socket ();
Try {
S. connect (New inetsocketaddress ("10.16.6.163", 5001), 3000); // 10.16.6.163 is the IP address of the PC, 5001 is the port number (consistent with the port number listened by the server ), 3000 indicates the connection timeout (3 seconds)
Message MSG = new message (); // specifies the handler object to be returned for instantiation.
Usermessage um = new usermessage (); // used as the data receiving object
If (! S. isconnected () {// if the connection fails
MSG. What = 0;
} Else {
MSG. What = 1;
Objectoutputstream OOS = new objectoutputstream (S. getoutputstream ());
Oos. writeobject (UD); // send the request
Objectinputstream OIS = new objectinputstream (S. getinputstream ());
Um = (usermessage) Ois. readobject (); // get the data packet
}
MSG. OBJ = Um; the object assigned to msg
Mhandler. removecallbacksandmessages (msg. OBJ );
Mhandler. sendmessage (MSG); // return to handler
} Catch (exception e ){
E. printstacktrace ();
}
}
}
The job of this thread is to maintain communication with the server to obtain and send messages.
Next, let's take a look at the activity for retrieving images.
Pictureshow. Java:
Package com. xluo. pcphone;
Import com. xluo. Common. userdata;
Import com. xluo. Common. usermessage;
Import com. xluo. Socket. usersocket;
Import Android. App. activity;
Import Android. Graphics. Bitmap;
Import Android. Graphics. bitmapfactory;
Import Android. OS. Bundle;
Import Android. OS. Handler;
Import Android. OS. message;
Import Android. View. window;
Import Android. widget. imageview;
Import Android. widget. Toast;
Public class pictureshow extends activity {
Private imageview IV = NULL;
Private userdata UD = new userdata ();
Private handler mhandler = new handler (){
Public void handlemessage (Message MSG ){
Switch (msg. What ){
Case 1:
Usermessage um = (usermessage) msg. OBJ; // get the data packet
Byte [] B = Um. getb (); // extract the image stream from the data packet
If (B. length! = 0 ){
Bitmap Bm = getbitmap (B); // convert to bitmap
Iv. setimagebitmap (BM); // display the image
}
Break;
Case 0:
Toast. maketext (pictureshow. This, "failed to connect to the server! ", Toast. length_short );
}
}
};
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Requestwindowfeature (window. feature_no_title );
Setcontentview (R. layout. screen_picture );
IV = (imageview) findviewbyid (R. Id. screen_picture_img );
UD. setgetpicture (true );
New usersocket (mhandler, UD). Start ();
Toast. maketext (pictureshow. This, "press back to return", Toast. length_short );
}
Private bitmap getbitmap (byte [] B) {// converts a binary image to a bitmap
If (B. length! = 0)
{
Return bitmapfactory. decodebytearray (B, 0, B. Length );
} Else {
Return NULL;
}
}
}
The instance has basically been completed, and the function is very simple, and there is no beautiful scientific research, just for the same cainiao as me to encourage you, if there is a hero to visit, also hope to give advice. I learned PHP at school. Now I have to work hard on Java and play android. Now, just like socialism in China, we are in the initial stage and need to learn many things. I am a cool cainiao. I hope you will give me more criticism!
(Appendix: If reprinted, please specify the source !)