Android client communicates with the server through socket

Source: Internet
Author: User

The following is a demo. The Android client communicates with the server through socket.

Because the java. Io. * package and java.net. * package can be fully used in Android, the logic part is actually no different from j2se. But the UI code is different.

The android client uses Socket to communicate with the server in the following five steps:

(1) instantiate a socket through an IP address and port and request to connect to the server;

 Socket = new socket ("10.14.114.127", 54321); // ip: 10.14.114.127, port 54321

(2) obtain the socket stream for reading and writing, and package the stream into bufferwriter or printwriter.

Printwriter out = new printwriter (New bufferedwriter (New outputstreamwriter (socket. getoutputstream (), true );

There are three classes involved: Socket. getoutputstream to get the socket output byte stream, outputstreamwriter is the bridge between byte flow to swap Stream Conversion, bufferwriter is a swap stream, and then packaged into printwriter.

(3) read and write socket

Out. println (Message );

 

(4) Close the opened stream

Out. Close ();

The complete project code is as follows:

Package COM. yarin. android. examples_08_04; </P> <p> Import Java. io. bufferedreader; <br/> Import Java. io. bufferedwriter; <br/> Import Java. io. inputstreamreader; <br/> Import Java. io. outputstreamwriter; <br/> Import Java. io. printwriter; <br/> Import java.net. socket; </P> <p> Import android. app. activity; <br/> Import android. OS. bundle; <br/> Import android. util. log; <br/> Import android. view. view; <br/> Import androi D. view. view. onclicklistener; <br/> Import android. widget. button; <br/> Import android. widget. edittext; <br/> Import android. widget. textview; </P> <p> public class activity01 extends activity <br/>{< br/> private final stringdebug_tag = "activity01 "; </P> <p> private textviewmtextview = NULL; <br/> private edittextmedittext = NULL; <br/> private buttonmbutton = NULL; <br/>/** called when the activity is first c Reated. */<br/> @ override <br/> Public void oncreate (bundle savedinstancestate) <br/>{< br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); </P> <p> mbutton = (button) findviewbyid (R. id. button01); <br/> mtextview = (textview) findviewbyid (R. id. textview01); <br/> medittext = (edittext) findviewbyid (R. id. edittext01); </P> <p> // login <br/> mbutton. setonclicklistener (New onclicklistener () <br />{< Br/> Public void onclick (view v) <br/>{< br/> Socket socket = NULL; <br/> string message = medittext. gettext (). tostring () + "/R/N "; <br/> try <br/> {<br/> // create a socket <br/> // socket = new socket ("192.168.1.110", 54321 ); <br/> socket = new socket ("10.14.114.127", 54321); // ip: 10.14.114.127, port 54321 <br/> // send a message to the server <br/> printwriter out = new printwriter (New bufferedwriter (New outputstreamwriter (socket. g Etoutputstream (), true); <br/> out. println (Message); </P> <p> // receives messages from the server <br/> bufferedreader BR = new bufferedreader (New inputstreamreader (socket. getinputstream (); <br/> string MSG = BR. readline (); </P> <p> If (MSG! = NULL) <br/>{< br/> mtextview. settext (MSG); <br/>}< br/> else <br/>{< br/> mtextview. settext ("data error! "); <Br/>}< br/> // close the stream <br/> out. close (); <br/> Br. close (); <br/> // close the socket <br/> socket. close (); <br/>}< br/> catch (exception e) <br/>{< br/> // todo: handle exception <br/> log. E (debug_tag, E. tostring (); <br/>}< br/>}); <br/>}< br/>

Layout file main. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: Orientation = "vertical" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "fill_parent" <br/> <textview <br/> Android: id = "@ + ID/textview01" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: TEXT = "The message sent from the server is displayed here" <br/> <edittext <br/> Android: id = "@ + ID/edittext01" <br/> Android: text = "Enter the content to be sent" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content"> <br/> </edittext> <br/> <button <br/> Android: id = "@ + ID/button01" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: TEXT = "send" <br/> </linearlayout>

The androidmanifest. xml file is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <manifest xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> package = "com. yarin. android. examples_08_04 "<br/> Android: versioncode =" 1 "<br/> Android: versionname =" 1.0 "> <br/> <application Android: icon = "@ drawable/icon" Android: Label = "@ string/app_name"> <br/> <activity Android: Name = ". activity01 "<br/> Android: Label =" @ string/app_name "> <br/> <intent-filter> <br/> <action Android: Name =" android. intent. action. main "/> <br/> <category Android: Name =" android. intent. category. launcher "/> <br/> </intent-filter> <br/> </activity> <br/> </Application> <br/> <uses-Permission Android: name = "android. permission. internet "> </uses-Permission> <br/> <uses-SDK Android: minsdkversion =" 5 "/> <br/> </manifest>

Of course, there are also server-side code

Package COM. yarin. android. examples_08_04; </P> <p> Import Java. io. bufferedreader; <br/> Import Java. io. bufferedwriter; <br/> Import Java. io. inputstreamreader; <br/> Import Java. io. outputstreamwriter; <br/> Import Java. io. printwriter; <br/> Import java.net. serversocket; <br/> Import java.net. socket; </P> <p> public class server implements runnable <br/> {<br/> Public void run () <br/>{< br/> try <br/> {<br/> // create a serversocket <br/> serversocket = new serversocket (54321 ); <br/> while (true) <br/> {<br/> // accept client requests <br/> Socket Client = serversocket. accept (); <br/> system. out. println ("accept "); <br/> try <br/> {<br/> // receives client messages <br/> bufferedreader in = new bufferedreader (New inputstreamreader (client. getinputstream (); <br/> string STR = in. readline (); <br/> system. out. println ("read:" + Str); <br/> // send a message to the server <br/> printwriter out = new printwriter (New bufferedwriter (New outputstreamwriter (client. getoutputstream (), true); <br/> out. println ("Server Message"); <br/> // close the stream <br/> out. close (); <br/> in. close (); <br/>}< br/> catch (exception e) <br/>{< br/> system. out. println (E. getmessage (); <br/> E. printstacktrace (); <br/>}< br/> finally <br/>{< br/> // close <br/> client. close (); <br/> system. out. println ("close"); <br/>}< br/> catch (exception E) <br/>{< br/> system. out. println (E. getmessage (); <br/>}< br/> // main function, enabling the server <br/> Public static void main (string a []) <br/>{< br/> thread topics topserverthread = new thread (new server (); <br/> topics topserverthread. start (); <br/>}< br/>

Enable the server code first,

Java Server

Then start the android simulator. Running result

This is the android client. Enter 12345 and click send:

 

 

This is the message received by the 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.