Android first Knowledge socket communication--java program do server

Source: Internet
Author: User

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

Related Article

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.