A socket is also called a socket. It is used to describe the IP address and port and is a communication connection handle. Applications usually send requests to or respond to network requests through sockets
To initiate a communication, a client must first know the Host IP address and communication port of the running server. Then, the network infrastructure uses the target address to transmit the information sent by the client to the correct host. in Java, the address can be defined by a string, A string can be a numeric address (for example, 192.168.1.108), a host name, and Port 6000.
In the following example, the mobile phone number is the client, the PC (Linux system) is the server, and the mobile phone number and the server are agreed to be a port number of 6000. the mobile phone sends a command to the server through socket. The server listens to Port 6000, receives the Socket socket from the client, executes the command, and returns the command to the mobile client. The mobile client receives messages from the server and displays the messages. In this way, the server sends commands from the mobile phone end and displays the results after the server executes the commands. In this way, you can use a mobile phone to control the running of the server, such as restarting, shutting down, and viewing files.
Instance:
Server
Package COM. android. server; import Java. io. bufferedreader; import Java. io. bufferedwriter; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. outputstreamwriter; import java.net. serversocket; import java.net. socket; import Java. io. linenumberreader; public class Server extends thread {private serversocket Server = NULL; Private Static final int Port = 6000; private bufferedwriter write R; private bufferedreader reader; private server () throws ioexception {// create socket server createsocket ();} public void run () {Socket Client; string txt; try {// infinite loop of threads, real-time listening to the socket port while (true) {client = responsesocket (); // response to the client link request .. While (true) {TXT = receivemsg (client); // link to obtain the command system. Out. println (txt) from the client; If (txt! = NULL) {// Execute Command TXT = excecommand (txt);} // return the message sendmsg (client, txt) to the client; // interrupt, close the break of the connection ;} closesocket (client) ;}} catch (ioexception e) {system. out. println (e) ;}// create a serversocket instance and bind it to a specific port. A server port can support up to 50 connections. If the port is exceeded, the connection is rejected. // Therefore, up to 50 clients can simultaneously send messages to the server using the specified port private void createsocket () throws ioexception {Server = new serversocket (port); system. out. println ("server starting .. ");}/* serversocket: This class implements a server socket, which can be used to listen to requests from the network. 1. Create a serversocket: serversocket (INT localport) serversocket (INT localport, int queuelimit) serversocket (INT localport, int queuelimit, inetaddress localaddr) must specify a port to create a serversocket, so that the client can send a connection request to the port number. Valid port range: 0-65535 2. The serversocket operation socket accept () void close accept () method creates a socket instance for the next incoming connection request, return the successfully connected socket instance to the server socket. If no connection request is sent, the accept () method blocks the wait. The close method is used to close the socket */private socket responsesocket () throws ioexception {Socket Client = server. accept (); system. out. println ("Client Connected .. "); Return client;} // close socketprivate void closesocket (Socket socket) throws ioexception {reader. close (); writer. close (); Socket. close (); system. out. println ("client closed .. ");} // send the message private void sendmsg (Socket socket, string MSG) throws ioexception {writer = new bufferedwriter (New outputstreamwriter (socket. getoutputstream (); writer. write (MSG + "\ n"); writer. flush ();} // receives messages from the client. The server uses server. accept (); receives the socket from the client, uses the I/O Method // retrieves the message from the socket private string receivemsg (Socket socket) throws ioexception {reader = new bufferedreader (New inputstreamreader (socket. getinputstream (); system. out. println ("server get input from client socket .. "); string line = NULL; while (line = reader. readline ())! = NULL) {system. Out. println (line); return line;} // run the Command sent by the client. The server will execute the message (command) sent from the client on the local machine ). // Return the result returned by the server after the command is executed. For example, if you run the "ls" command in Linux, the private string excecommand (string command) {string MSG = "" is returned for all files in the current directory ""; try {// runtime. getruntime () returns the runtime object of the current application. The Exec () // method of this object instructs the Java Virtual Machine to create a sub-process to execute the specified executable program (command ), and return the process object instance corresponding to the sub-process. // You can use process to control the execution of the sub-process or obtain the information of the sub-process. Process = runtime.getruntime(.exe C (command); inputstreamreader IR = new inputstreamreader (process. getinputstream (); linenumberreader input = new linenumberreader (IR); string line; while (line = input. readline ())! = NULL) {system. out. println (line); MSG + = line + "\ n" ;}} catch (Java. io. ioexception e) {system. err. println ("ioexception" + E. getmessage ();} return MSG;} public static void main (final string ARGs []) throws ioexception {server commandserver = new server (); If (commandserver! = NULL) {// commandserver. Stop (); commandserver. Start ();}}}
Mobile client:
Package COM. control; import Java. io. bufferedreader; import Java. io. bufferedwriter; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. outputstreamwriter; import java.net. inetsocketaddress; import java.net. socket; import java.net. unknownhostexception; import android. app. activity; import android. app. alertdialog; import android. content. context; import android. content. dialoginterface; impo RT android. content. sharedpreferences; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. text. textutils; import android. text. method. scrollingmovementmethod; import android. util. log; import android. view. keyevent; import android. view. menu; import android. view. menuitem; import android. view. view; import android. widget. button; import android. widget. edittext; import androi D. widget. textview; public class controlactivity extends activity {// server IP address public static final string defult_pres = "192.168.1.108"; public static final string prefs_name = "preferencesfile"; public static final int connented = 0; public static final int updatalog = 1; Private Static final int Port = 6000; private edittext command; private edittext ipedit; private textview log; private button send; private Button clean; private string IP; private string logmsg; private Socket socket; private bufferedwriter writer; private inetsocketaddress ISA = NULL; Context mcontext; Public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); mcontext = This; findviews (); setonclick (); Init ();} public void findviews () {command = (edittext) This. findviewbyid (R. id. command ); Log = (textview) This. findviewbyid (R. id. log); send = (button) This. findviewbyid (R. id. send); ipedit = (edittext) This. findviewbyid (R. id. ipedit); clean = (button) This. findviewbyid (R. id. clean);} private void Init () {log. setmovementmethod (scrollingmovementmethod. getinstance (); logmsg = log. gettext (). tostring (); // create a socket instance socket = new socket (); IP = onload (); If (IP! = NULL) {ipedit. settext (IP) ;}} private void setonclick () {send. setonclicklistener (new view. onclicklistener () {public void onclick (view v) {IP = ipedit. gettext (). tostring (); // when the send button is clicked, A tcpclient thread is enabled to send the message tcpclient TCP = new tcpclient (command. gettext (). tostring (); TCP. start () ;}}); clean. setonclicklistener (New button. onclicklistener () {public void onclick (view v) {// todo auto-generated method stubl Ogmsg = ""; log. settext (logmsg) ;}}) ;}// you must link to the server before sending a message to the server. Public void connecttoserver () throws unknownhostexception, ioexception {socket = requestsocket (IP, Port); // determine whether the link is successful if (socket. isconnected () {message MSG = new message (); MSG. what = connented; mhandler. sendmessage (MSG) ;}// link to the server private socket requestsocket (string host, int port) throws unknownhostexception, ioexception {socket consocket = new socket (); // create a socket address, the IP address is a wildcard address and the port number is the specified value. // Valid ports are between 0 and 65535. Zero port number allows the system to select a temporary port in the BIND operation. ISA = new inetsocketaddress (host, Port); // create a remote connection consocket. connect (ISA); Return consocket;} // send the message private void sendmsg (Socket socket, string MSG) throws ioexception {writer = new bufferedwriter (New outputstreamwriter (socket. getoutputstream (); log. I ("MSG", MSG. replace ("\ n", "") + "\ n"); writer. write (MSG. replace ("\ n", "") + "\ n"); writer. flush ();} // receive server information private string receivemsg (Socket socket) Throws ioexception {bufferedreader reader = new bufferedreader (New inputstreamreader (socket. getinputstream (); string line; string TXT = ""; while (line = reader. readline ())! = NULL) {TXT + = line + "\ n";} reader. close (); Return txt;} class tcpclient extends thread {string commandstring; Public tcpclient () {commandstring = "ls" ;}public tcpclient (string command) {commandstring = command ;} public void run () {string Recv; try {connecttoserver (); // send the command sendmsg (socket, commandstring) to the server; // wait, receive message Recv = receivemsg (socket); If (Recv! = NULL) {logmsg + = Recv; // close bufferedwriter and socketwriter. close (); socket. close (); // display the message returned by the server. Message MSG = new message (); MSG. what = updatalog; mhandler. sendmessage (MSG) ;}} catch (unknownhostexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}} private string onload () {sharedpreferences settings = getsharedpreferences (prefs_name, 0); string mpreferences = Setting S. getstring ("Preferences", defult_pres); Return mpreferences;} private void onsave (string save) {If (textutils. isempty (SAVE) {setpreferences (defult_pres) ;}else {setpreferences (SAVE) ;}} private void setpreferences (string mpreferences) {sharedpreferences settings = values (prefs_name, 0 ); sharedpreferences. editor editor = settings. edit (); Editor. putstring ("Preferences", mpreferences); edito R. commit ();} public Boolean onkeydown (INT keycode, keyevent event) {If (event. getkeycode () = keyevent. keycode_back) {alertdialog. builder = new alertdialog. builder (this); builder. settitle ("PC control"); builder. setmessage ("exit? "); Builder. setpositivebutton ("yes", new dialoginterface. onclicklistener () {public void onclick (dialoginterface Diener, int which) {onsave (ipedit. gettext (). tostring (); finish () ;}}); builder. setnegativebutton ("cancel", new dialoginterface. onclicklistener () {public void onclick (dialoginterface dialog, int which) {}}); builder. show ();} return Super. onkeydown (keycode, event);} public Boolean oncreateoptionsmenu (menu) {menu. add (0, 1, 1, "shutdown"); menu. add (0, 2, 2, "restart"); menu. add (0, 3, 3, "quit"); return Super. oncreateoptionsmenu (menu);} public Boolean onoptionsitemselected (menuitem item) {Switch (item. getitemid () {Case 1: tcpclient TCP = new tcpclient ("sudo poweroff"); TCP. start (); Return true; Case 2: TCP = new tcpclient ("sudo reboot"); TCP. start (); Return true; Case 3: Finish (); break;} return Super. onoptionsitemselected (item);} handler mhandler = new handler () {public void handlemessage (Message MSG) {Switch (MSG. what) {Case connented: logmsg + = "server connented \ n"; log. settext (logmsg); break; Case updatalog: log. settext (logmsg); log. setscrollcontainer (true); break ;}}};}
Remember to register permissions in androidmanifest. xml
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Now, you can try it on your computer. If you have any questions, please share them and learn from each other!
From http://www.eoeandroid.com/thread-148913-1-1.html