1. Create a new Java project to do server
Public classMyServer {String str; Public MyServer(){Try{//server-side declaration with serversocket, parentheses inside the port number, the port number is its own designatedServerSocket SS =NewServerSocket (4700);the//accept method will always wait for the client to connect in hereSocket accept = Ss.accept ();//Create a new read stream, the character set is Utf-8BufferedReader br =NewBufferedReader (NewInputStreamReader (Accept.getinputstream (),"Utf-8"));//Use this method to read the data written by the clientstr = Br.readline (); System. out. println ("Data from the client:"+ str); Br.close (); }Catch(IOException e) {E.printstacktrace (); } } Public Static void Main(String [] args) {//Don't forget this step NewMyServer (); }}
2. Create a new Android project as a client
Public class mainactivity extends Activity { @Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//There are many reasons to use the child thread here, you can learn about Baidu NewThread () { Public void Run() {Try{//cmd ipconfig get the current native IP addressSocket client =NewSocket ("192.168.56.1",4700);//Be sure to end with a newline character, otherwise readline will always read and will not stop, so Reaeline has no value to returnString str ="Hello server \ n"; BufferedWriter BW =NewBufferedWriter (NewOutputStreamWriter (Client.getoutputstream ())); Bw.write (str); Bw.flush (); Bw.close (); }Catch(Unknownhostexception e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); }}}.start (); }
Android first Knowledge socket communication--java program do server