In the Android through the socket to connect the server, is a relatively simple way of network connection, although the use of not much, but some occasions is very convenient, here to summarize the basic wording.
Client:
try {Socket socket = new socket (host, port); Socket.setsotimeout (6 * 1000); PrintWriter printwriter = new PrintWriter (Socket.getoutputstream (), True);p rintwriter.println ("Socket test"); Printwriter.flush (); BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.getinputstream (), "GBK")); revmsg = Reader.readline (); if (Textutils.isempty (revmsg)) {revmsg = "Server Error";} Printwriter.close (); Reader.close (); Socket.close (); return revmsg;} catch (Exception e) {e.printstacktrace (); revmsg = "Server Error";}
Server-side:
Import Java.net.serversocket;import Java.net.socket;public class Server {public static void main (string[] args) {try {Ser Versocket ServerSocket = new ServerSocket (8888), while (true) {Socket socket = serversocket.accept (); New Serverthread ( socket);}} catch (Exception e) {e.printstacktrace ();}}}
Import Java.io.bufferedreader;import Java.io.filewriter;import Java.io.ioexception;import Java.io.inputstreamreader;import java.io.printwriter;import Java.net.socket;class ServerThread extends Thread { Private Socket socket;private bufferedreader bufferedreader;private printwriter printwriter;public ServerThread ( Socket socket) throws IOException {this.socket = Socket;bufferedreader = new BufferedReader (New InputStreamReader (socket . getInputStream ()));p Rintwriter = new PrintWriter (Socket.getoutputstream (), true); System.out.println ("Client (" + getName () + ") connected ..."); Start ();} @Overridepublic void Run () {try {String line = Bufferedreader.readline (), if (!line.equals ("Exit")) {System.out.println ( "Client (" + getName () + ") say:" + line); Writetotxt (line + "\ r \ n", "/local/data.txt");p rintwriter.println ("Receive success!");} Printwriter.close (); Bufferedreader.close (); Socket.close ();} catch (IOException e) {}}private void Writetotxt (String str, string path) {try {FileWriter writer = new FilewRiter (path, true); Writer.write (str); Writer.close ();} catch (IOException e) {e.printstacktrace ();}}}
The server side handles multiple concurrent socket requests through multithreading.
The demo is simple.
Above.
Android socket and Server communication Universal Demo